javascript jQuery 的 attr() 和 getAttribute() 的区别
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8149203/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Difference between jQuery's attr() and getAttribute()
提问by James Allardice
The jQuery documention for the attr
method states that:
该attr
方法的 jQuery 文档指出:
Attribute values are strings with the exception of a few attributes such as value and tabindex.
属性值是字符串,但少数属性(例如 value 和 tabindex)除外。
And that does seem to be the case. Consider the following element:
情况似乎确实如此。考虑以下元素:
<input type="text" id="example" tabindex="3">
The following line does indeed show "number", not "string":
以下行确实显示“数字”,而不是“字符串”:
alert(typeof $("#example").attr("tabindex")); //Number
Now, the thing that's confusing me is that when using the DOM method getAttribute
, you get a different result:
现在,让我感到困惑的是,当使用 DOM 方法时getAttribute
,您会得到不同的结果:
alert(typeof $("#example")[0].getAttribute("tabindex")); //String
Looking at the jQuery source for the attr
method, it appears that jQuery simply returns what getAttribute
returns, so why is there a difference? Here's the relevant lines of the jQuery source:
查看该attr
方法的 jQuery 源代码,似乎 jQuery 只是返回返回的内容getAttribute
,那么为什么会有区别呢?这是jQuery 源代码的相关行:
ret = elem.getAttribute( name );
// Non-existent attributes return null, we normalize to undefined
return ret === null ?
undefined :
ret;
And here's a fiddleto demonstrate the issue. Just to confuse matters further, I've tried it in Chrome 15, Firefox 8, IE8 and IE7, and all behave as described above, except for IE7, which alerts "number" for both (which is what I would expect to happen).
这是一个演示这个问题的小提琴。只是为了进一步混淆问题,我已经在 Chrome 15、Firefox 8、IE8 和 IE7 中尝试过,并且所有行为都如上所述,除了 IE7,它为两者发出“数字”警报(这是我期望发生的) .
采纳答案by Matt
Because jQuery defines a propHook for tabIndex
which explicity parseInt
's the return type;
因为 jQuery 定义了一个明确的返回类型的propHooktabIndex
;parseInt
return attributeNode && attributeNode.specified ?
parseInt( attributeNode.value, 10 ) :
rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ?
0 :
undefined;
This hook is then added to the attrHook
which is why the behaviour is observed in the attr
function (and why it first appears no attrHook is defined for tabIndex
).
然后将此钩子添加到 ,attrHook
这就是为什么在attr
函数中观察到行为的原因(以及为什么首先出现没有为 定义 attrHook 的原因tabIndex
)。