JS中attr和prop属性的区别

 我来答
育知同创教育
2016-08-12 · 百度知道合伙人官方认证企业
育知同创教育
1【专注:Python+人工智能|Java大数据|HTML5培训】 2【免费提供名师直播课堂、公开课及视频教程】 3【地址:北京市昌平区三旗百汇物美大卖场2层,微信公众号:yuzhitc】
向TA提问
展开全部
JS中attr和prop属性的区别如下:
1、attr是attribute的缩写,是一个特性节点,每个DOM元素都有一个对应的attributes属性来存放所有的attribute节点,attributes是一个类数组的容器,说得准确点就是NameNodeMap,总之就是一个类似数组但又和数组不太一样的容器。attributes的每个数字索引以名值对(name=”value”)的形式存放了一个attribute节点。
<div class="box" id="box" gameid="880">hello</div>
上面的div元素的HTML代码中有class、id还有自定义的gameid,这些特性都存放在attributes中,类似下面的形式:
[ class="box", id="box", gameid="880" ]
可以这样来访问attribute节点:
var elem = document.getElementById( 'box' );
console.log( elem.attributes[0].name ); // class
console.log( elem.attributes[0].value ); // box
2、与之对应的property属性,比较特殊的是一些值为Boolean类型的property,如一些表单元素:
<input type="radio" checked="checked" id="raido">
var radio = document.getElementById( 'radio' );
console.log( radio.getAttribute('checked') ); // checked
console.log( radio.checked ); // true
对于这些特殊的attribute节点,只有存在该节点,对应的property的值就为true,如:
<input type="radio" checked="anything" id="raido">
var radio = document.getElementById( 'radio' );
console.log( radio.getAttribute('checked') ); // anything
console.log( radio.checked ); // true
3、了更好的区分attribute和property,基本可以总结为attribute节点都是在HTML代码中可见的,而property只是一个普通的名值对属性。
奔跑的窝牛的家
高粉答主

2016-08-12 · 每个回答都超有意思的
知道顶级答主
回答量:3.6万
采纳率:98%
帮助的人:4263万
展开全部

 window或document中使用.attr()方法在jQuery1.6中不能正常运行,因为window和document中不能有attributes。它们包含properties(比如:location或readyState),必须使用.prop()方法操作或简单地使用javascript原生的方法。 在jQuery1.6.1中,window和document中使用.attr()将被自动转成使用.prop(还没试过)。其次,checked,selected和前面提到的其它boolean attributes,因为这些attributes和其相应的properties之间的特殊关系而被特殊对待。通常,attribute 就是以下html代码中看到的,如:


             <input type=”checkbox” checked=”checked”>


  但它仅表示checked属性在页面加载的时候被设置成默认值或初始值,而不管checkbox元素是否被选中。 而通常 properties 是一个浏览器用来记录当前属性值的东西。正常情况下,properties反映它们相应的attributes。


  所以,当用户点击一个checkbox元素或选中一个select元素的一个option时,使得properties保持最新,但对应的attributes却不一定,它仅被浏览器用来保存该属性的初始值。

 一个例子:

<input type="radio" id="RdMale" checked="checked" name="sex" value="male" /><label for="hRdMale">男</label>
<input type="radio" id="RdFemale" name="sex" value="female" /><label for="hRdFemale">女</label>
<button id="reSet">重置</button>

jQ代码

$("#reSet").click(function() {
  $("input[name='sex']:first").attr("checked",true);
});

但这样写火狐浏览器不支持,
添加属性名称该属性就会生效应该使用.prop()

$("input[name='sex']:first").prop("checked",true); //改成prop就成功了

   区别在于selectedIndex, tagName, nodeName, nodeType, ownerDocument, defaultChecked, 以及defaultSelected 等属性需用.prop()方法。  添加属性名称该属性就会生效应该使用.prop()

本回答被提问者采纳
已赞过 已踩过<
你对这个回答的评价是?
评论 收起
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式