element节点的attribute和property初探

最近在用jquery的时候,发现$('input[checked="checked"]')有时候不能正确的选择被勾选的checkbox.
所以调查了一下

在javascript里,任何一个obj都有property,并且可以任意添加

var o=new Object();
o.name='crap';
alert(typeof(o.name));

显示是个string

对于element元素,有个readonly的property,叫做attributes,这是个NamedNodeMap.
[url]http://www.w3schools.com/dom/prop_element_attributes.asp[/url]
[url]http://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-745549614[/url]
element元素可以通过getAttribute,setAttribute来操作attributes这个NamedNodeMap里的内容
以下内容是在火狐18.0.1演示的.


<script type="text/javascript">
function crap() {
var item = document.getElementById("key");
alert(item.type);
alert(item.getAttribute('type'));
}
</script>
<input type="text" id="key">
<button onclick="crap()">button</button>

看到输出都是text,因为item.type这个属性是由它的html attributes暴露的
[url]http://www.w3.org/TR/DOM-Level-2-HTML/html.html#ID-642250288[/url]


var item = document.getElementById("key");
alert(item.type);
item.setAttribute('type','checkbox');
alert(item.type);

输出分别是text,checkbox,因为item.setAttribute('type','checkbox')更改了item.type属性

把代码改成如下

<script type="text/javascript">
function crap() {
var item = document.getElementById("key");
alert(item.checked);
alert(item.getAttribute('checked'));
}
</script>
<input type="checkbox" id="key">
<button onclick="crap()">button</button>

在checkbox没选中的情况下,输出分别为false,null
鼠标勾选以后,是true,null

IE7中分别是false,false
true,true

看来火狐没有进行setAttribute

我猜测这就是jquery中input[checked='checked'] selector有时候不能选中被勾选的元素的原因,
要用:checked这个选择器.

不过换句话说,一个checkbox元素e被勾选以后,它到底应该e.checked=true才对,
还是e.setAttribute('checked','checked')?

规范说
[quote]
The attributes are exposed as properties for compatibility with DOM Level 0.
This usage is deprecated because it can not be generalized to all possible attribute names for XML.
We recommend the use of generic methods on the core Element interface for setting, getting and removing attributes.
[/quote]
那岂不是火狐应该setAttribute('checked','checked')?
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值