jQuery 的 attr() 除了單獨設定一個屬性,也能傳入物件一次批次設定多組。這在需要同時改寫連結的 href 與 title 這類情境特別方便。
<!DOCTYPE html>
<html>
<head>
<script src="js/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("#w3s").attr({
"href" : "https://www.jb51.net/list/list_172_1.htm",
"title" : "jb51.net"
});
});
});
</script>
</head>
<body>
<p><a href="https://www.jb51.net/list/list_172_1.htm" id="w3s">jb51.net</a></p>
<button>點此改變連結與提示</button>
<p>滑鼠移過連結即可看到 title 提示已更新。</p>
</body>
</html>
// 1. 取得屬性值
var href = $("#w3s").attr("href");
// 2. 設定單一屬性
$("#w3s").attr("title", "新標題");
// 3. 一次設定多個屬性
$("#w3s").attr({ "href": "/new", "title": "新標題", "target": "_blank" });
這是 jQuery 1.6 之後最重要的觀念區別:
最典型的例子是 checkbox:
// 讀取使用者「目前」是否勾選,要用 prop
var checked = $("#agree").prop("checked");
// attr("checked") 只會告訴你 HTML 上「當初」有沒有寫 checked
實務上的判斷準則:checked、selected、disabled 這類會隨使用者互動變化的,一律用 prop();href、title、class、data-* 這類純粹的標示性屬性,用 attr() 即可。
key 加引號:物件寫法中若屬性名稱含連字號(如 data-role、aria-label),必須用引號包住,否則會被當成減法運算式。
移除屬性用 removeAttr():
$("#w3s").removeAttr("target");
自訂資料用 data():讀寫 data-* 屬性時,.data() 比 .attr() 更方便,因為它會自動把 "true"、"3"、"[1,2]" 轉成對應的布林、數字與陣列:
<div id="box" data-count="5" data-active="true"></div>
var n = $("#box").data("count"); // 數字 5,而非字串 "5"
class 類屬性另有專用方法:新增移除 class 請用 addClass()/removeClass()/toggleClass()。用 attr("class", ...) 會整組覆寫,把既有的 class 全部沖掉。