jquery之attr與prop方法的區別
阿新 • • 發佈:2018-11-20
在jquery1.6版本之前,如果使用attr方法去設定沒有被設定的屬性,會返回undefined,在jquery1.6版本之後,為獲取並改變DOM的checked、disabled、selected等布林屬性,出現了prop()方法,使用prop方法,如果這三個值沒有設定,返回的是false,設定之後返回true。
官方API的說法:
Cross-browser consistency: The values of some attributes are reported inconsistently across browsers, and even across versions of a single browser. The .attr()
method reduces such inconsistencies.
prop()方法與attr()方法用法一致,語法如下:
1. attr(name,value)
栗子:
$(function() { // 設定單個屬性 $("img").attr("alt","頭破了"); $("img").attr("title","錯錯錯"); // 設定多個屬性 $("img").attr({ alt: "頭破了"; title: "錯錯錯" }) });
2. prop(name,value)
栗子:
$(function () {
$("input").eq(0).click(function () {
$("#ck").prop("checked", true);
});
});