jQuery的attr()和getAttribute()之间的区别

Jam*_*ice 10 javascript jquery dom

attr方法的jQuery文档声明:

属性值是字符串,但有一些属性除外,例如value和tabindex.

似乎确实如此.考虑以下元素:

<input type="text" id="example" tabindex="3">
Run Code Online (Sandbox Code Playgroud)

以下行确实显示"数字",而不是"字符串":

alert(typeof $("#example").attr("tabindex")); //Number
Run Code Online (Sandbox Code Playgroud)

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

alert(typeof $("#example")[0].getAttribute("tabindex")); //String
Run Code Online (Sandbox Code Playgroud)

看一下该attr方法的jQuery源代码,看起来jQuery只返回getAttribute返回值,那为什么会有区别呢?这是jQuery源代码相关行:

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

这是展示这个问题的小提琴.只是为了进一步混淆问题,我已经在Chrome 15,Firefox 8,IE8和IE7中尝试了它,并且所有行为如上所述,除了IE7,它警告两者的"数字"(这是我期望发生的) .

Mat*_*att 11

因为jQuery定义了一个propexook,tabIndex其中明确parseInt的是返回类型 ;

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

然后将此钩子添加到attrHook这就是为什么在attr函数中观察到行为的原因(以及为什么它首次出现时没有定义attrHooktabIndex).

  • 您应该链接到某个标记,而不是主分支.否则,行号可能在将来发生变化. (3认同)