JQuery关键字"this"没有得到属性值

JQuery keyword "this" does not get attribute value

我正在使用 JQuery 关键字 this。

我遇到了一些我不明白的事情。 这是我的代码:

<body>  
    <a id="link_1">jQuery.com</a>

    <!-- adding JQUERY -->  
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>            
    <!-- my JavaScript -->      
    <script>
      $("a").attr("href", "target_1");  
      $("a").attr("new_attribute", "new_attribute_value");

      $(function ($) {          
        $("a").mouseenter(function(){
                alert(this.id);
                alert(this.href);
                alert(this.new_attribute);          
         });        
       });  
    </script> 
</body>

我想 JQuery 将 id、href 和我的 new_attribute 作为提醒消息 return。

我可以调用关键字 'this'(使用 this.id)的 id,它按预期工作。 我还可以在关键字 this 上调用 href(使用 this.href)并且它按预期工作(即使我只使用 JQuery(不是内联)设置 href 的值)。

然而,对于新属性 "new_attribute",这种设置和获取无法按预期工作。

我的问题:我做错了什么?是否只能在关键字 'this'.

上调用 'certain /limited' 属性

这是因为 new_attribute 不是一个有效的属性。

一些内置属性会映射到属性,当您这样做时

this.id

您真正得到的是 id 属性,而不是

的属性
this.getAttribute('id')

你可以做到

this.getAttribute('new_attribute')

但是你真的应该使用 data-* 属性,而不是自己编造,但是 jQuery 的 data() 在内部映射数据并且不添加属性,但是在你的情况可能就是你想要的,只需在元素上存储任意数据

$("a").attr("href", "target_1");  
$("a").data("new_attribute", "new_attribute_value");

$(function ($) {          
    $("a").mouseenter(function(){
            alert(this.id);
            alert(this.href);
            alert( $(this).data('new_attribute') );
    });        
});  

你需要把this当作一个选择器,所以写成$(this)

在这个上下文中this指向HTMLAnchorElement对象,这里的问题是HTMLElement attributes和它们的属性之间的区别。简单地说,属性被呈现为 HTML 的一部分,并用于 HTML 标记一侧的额外对象声明配置。

另一方面,对象有属性,并不总是有相应的属性。有时会,但大多数情况下不会。

您可以像 new_attribute 一样将任意属性设置为 HTML 元素,但此自定义属性值不会成为对象 属性。因此读取 属性 这样的自定义属性将产生 undefined.

"this" 指的是 DOM 元素(尝试 console.log(this))。元素公开其 id 属性,如您在此处所见:https://developer.mozilla.org/en-US/docs/Web/API/element

因为是A元素,所以也暴露了它的href属性。但它永远不知道您的自定义属性。所以不能暴露。

在你的事件处理程序中试试这个:

var $this = $(this);
alert($this.attr('new_attribute'));

您的问题是您使用 attr() 方法设置了一个属性,但您通过调用 jQuery 的 prop() 的等效方法来查询(获取)它.

因为这是一个非标准属性,锚 <a> 元素的主接口 HTMLAnchorElement 或它在 DOM 中继承的其他接口不 have/implement 一个 new_attribute 属性 到位,您的 this.new_attribute 将始终 return undefined

但是,如果您想继续试验 this 关键字,您可以按照这些思路尝试一些东西 this.attributes['new_attribute'],这样您的编码之旅就不会再有任何不愉快的惊喜了:)