您的位置:首页 > Web前端 > JQuery

jquery 中prop()函数

2016-07-04 17:29 465 查看
prop()
函数用于设置或返回当前jQuery对象所匹配的元素的属性值。

该函数属于
jQuery
对象(实例)。如果需要删除DOM元素的属性,请使用removeProp()函数。

<div id="n1">
    <p id="n2" class="demo test" data-key="UUID" data_value="1235456465">CodePlayer</p>
    <input id="n3" name="order_id" type="checkbox" value="1">
    <input id="n4" name="order_id" type="checkbox" checked="checked" value="2">
</div>

var $n2 = $("#n2");
// prop()操作针对的是元素(Element对象)的属性,而不是元素节点(HTML文档)的属性
document.writeln( $n2.prop("data-key") ); // undefined
document.writeln( $n2.prop("data_value") ); // undefined

document.writeln( $n2.prop("id") ); // n2
document.writeln( $n2.prop("tagName") ); // P
document.writeln( $n2.prop("className") ); // demo test
document.writeln( $n2.prop("innerHTML") ); // CodePlayer
document.writeln( typeof $n2.prop("getAttribute") ); // function

// prop()设置的属性也是针对元素(Element对象),因此也可以通过元素本身直接访问
$n2.prop("prop_a", "CodePlayer");
document.writeln( $n2[0].prop_a ); // CodePlayer
var n2 = document.getElementById("n2");
document.writeln( n2.prop_a ); // CodePlayer

// 以对象形式同时设置多个属性,属性值可以是对象、数组等任意类型
$n2.prop( {
    prop_b: "baike",
    prop_c: 18,
    site: { name: "CodePlayer", url: "http://www.365mini.com/" }
} );
document.writeln( $n2[0].prop_c ); // 18
document.writeln( $n2[0].site.url ); // http://www.365mini.com/ 
// 反选所有的复选框(没选中的改为选中,选中的改为取消选中)
$("input:checkbox").prop("checked", function(index, oldValue){
    return !oldValue;
});

prop()与attr()的区别

prop()
函数针对的是DOM元素(JS
Element对象)的属性,attr()函数针对的是DOM元素所对应的文档节点的属性。详情请查看jQuery函数attr()和prop()的区别


注意事项:



1、如果通过
prop()
函数更改<input>和<button>元素的
type
属性,在多数浏览器上将会抛出一个错误,因为该属性一般不允许在后期更改。

2、如果使用
prop()
函数操作表单元素的checked、selected、disabled等属性,如果该元素被选中(或禁用),则返回
true
,否则(意即HTML中没有该属性)返回
false


3、
prop()
函数还可以设置或返回DOM元素的
Element
对象上的某些属性,例如:tagName、selectedIndex、nodeName、nodeType、ownerDocument、defaultChecked和defaultSelected等属性。

4、在IE9及更早版本中,如果使用
prop()
函数设置的属性值不是一个简单的原始值(String、Number、Boolean),并且在对应的DOM元素被销毁之前,该属性没有被移除,则可能会导致内存泄漏问题。如果你只是为了存储数据,建议你使用data()函数,以避免内存泄漏问题。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  javascript jquery dom