JQuery $(this).attr("name") vs this.name

JQuery $(this).attr("name") vs this.name

本文关键字:name quot this vs attr JQuery      更新时间:2023-09-26

之间的主要区别是什么

$(this).attr("name")

this.name

技术解释是什么?

第一个从由DOM元素形成的jQuery对象中获取属性值。第二个直接从DOM元素获取属性,因此速度更快。您应该尽可能使用本机属性。

我知道你一定在想。。。这是一个性能问题。。。但不是。这是一个可靠性问题。

当你通过javascript访问DOM时,你不能直接访问DOM,你得到的是一个由W3C的HTML规范定义的接口。

http://www.w3.org/TR/DOM-Level-2-HTML/html.html#ID-798055546

HTMLElement接口仅定义此属性。

interface HTMLElement : Element {
    attribute DOMString       id;
    attribute DOMString       title;
    attribute DOMString       lang;
    attribute DOMString       dir;
    attribute DOMString       className;
};

因此,对于那些接口定义了属性"name"(很可能是输入)的元素,您只能调用"this.name"

这个简单的代码将让您了解可能出错的地方。

<a fakeAttr="Hola" id="myAnchor" data-mytext="Anyone?">Link</a>

$(function(){
  /* This gives you undefined */
  alert('Direct access: ' + $('#myAnchor')[0].fakeAttr);
  /* This gets the work done */
  alert('jQuery access: ' + $('#myAnchor').attr('fakeAttr'));
  $('#myAnchor').click(function(){
     /* This is of course empty */
     alert(this.fakeAttr);
  });
});    

http://jsbin.com/ganihali/1/edit

浏览器构建JavaScriptDOM代理对象的方式可能会有所不同。。。IE过去对开发人员更友好,可以解析DOM中的所有内容,然后将其作为现成的对象属性提供给开发人员。但那是史前时代,现在没有浏览器会给你自定义属性。甚至没有数据属性(HTML5有效)。

因此,我会非常小心地让我轻松快速地访问属性并使用框架(这是有原因的)。