jQuery的attr()和getAttribute()之间的区别 [英] Difference between jQuery's attr() and getAttribute()

查看:98
本文介绍了jQuery的attr()和getAttribute()之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

attr 方法的jQuery文档说明:

The jQuery documention for the attr method states that:


属性值是字符串,除了一些属性
,如value和tabindex。

Attribute values are strings with the exception of a few attributes such as value and tabindex.

似乎是这样。考虑以下元素:

And that does seem to be the case. Consider the following element:

<input type="text" id="example" tabindex="3">

以下行确实显示number,而不是string:

The following line does indeed show "number", not "string":

alert(typeof $("#example").attr("tabindex")); //Number

现在,令我困惑的是当使用DOM方法 getAttribute ,您会得到不同的结果:

Now, the thing that's confusing me is that when using the DOM method getAttribute, you get a different result:

alert(typeof $("#example")[0].getAttribute("tabindex")); //String

查看 attr的jQuery源代码方法,似乎jQuery只是返回什么 getAttribute 返回,那么为什么会有区别?以下是 jQuery源的相关行:

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:

ret = elem.getAttribute( name );
// Non-existent attributes return null, we normalize to undefined
return ret === null ?
         undefined :
         ret;

这里是一个小提琴来展示这个问题。只是为了进一步混淆事情,我已经在Chrome 15,Firefox 8,IE8和IE7中尝试过,并且都按照上述方式进行操作,除了IE7之外,这两个都提醒了数字(这是我预期会发生的)

And here's a fiddle to 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).

推荐答案

因为jQuery定义了一个 propHook for tabIndex 哪些显着性 parseInt 是返回类型;

Because jQuery defines a propHook for tabIndex which explicity parseInt's the return type;

return attributeNode && attributeNode.specified ?
  parseInt( attributeNode.value, 10 ) :
  rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ?
    0 :
    undefined;

这个钩子然后是 attrHook 中的blob / b4392c220af3da945a8b2d7b0053291956c97a17 / src / attributes.js#L486rel =noreferrer>这就是为什么在 attr 函数(为什么它首先出现没有attrHook被定义为 tabIndex )。

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).

这篇关于jQuery的attr()和getAttribute()之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆