自定義屬性是相對於內置屬性來說的。
JavaScript 操作
<input type="text" id="txtBox" displayName="123456" />
var obj = document.getElementById("txtBox");
// 讀取
obj.getAttribute("displayName");
obj.attributes["displayName"].nodeValue;
// 設置
obj.setAttribute("displayName ","123456");
obj.attributes["displayName"].nodeValue = "123456";
jQuery 操作
方法一:attr()
設置或返回被選元素的屬性值。
語法:
// 獲取值
$("img").attr("src");
// 設置值
$("img").attr("src","test.jpg");
// 設置多個值
$("img").attr({ src: "test.jpg", alt: "Test Image" });
// 把src屬性的值設置爲title屬性的值
$("img").attr("title", function() { return this.src });
方法二:data()
jQuery 1.4.3+
語法:
// 讀取標籤定義屬性 data-[key] = [value]
$("#id").data("key");
// 設置標籤定義屬性
$("#id").data("key", "value");
注:
使用data設置自定義屬性值,在html代碼中是看不到的,但可以正常使用。