jQuery关键字"this"没有获得属性值 [英] JQuery keyword "this" does not get attribute value

查看:50
本文介绍了jQuery关键字"this"没有获得属性值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在玩JQuery关键字this.

I am playing around with the JQuery keyword this.

我遇到了一些我不理解的东西.这是我的代码:

I have come across something I do not understand. Here is my code:

<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作为警报消息.

I want JQuery to return the id, href and my new_attribute as an alert message.

我可以在关键字"this"(带有this.id)上调用id,它可以按预期工作.我还可以在关键字this上调用href(使用this.href),它可以按预期工作(即使我仅使用JQuery设置了href的值(不是内联的)).

I can call the id on the keyword 'this' (with this.id) and it works as expected. I can also call the href on the keyword this (with this.href) and it works as expected (even though I set the value of href with JQuery only (an not inline)).

但是,使用新属性"new_attribute"进行这种设置&不能正常工作.

However with the new attribute "new_attribute" this kind of set & get does not work as expected.

我的问题:我做错了什么?只能在关键字"this"上调用"certain/limited"属性.

推荐答案

这是因为 new_attribute 不是有效的属性.

It's because new_attribute is not a valid attribute.

某些内置属性会映射到属性,并且在执行时会映射

Some built in attributes are mapped to properties, and when you do

this.id

您实际上得到的是 id 属性,而不是该属性,

you're really getting the id property, not the attribute, as that would be

this.getAttribute('id')

您可以做到

this.getAttribute('new_attribute')

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

but you should really be using data-* attributes, and not make up your own, but jQuery's data() maps data internally and doesn't add attributes, but in your case that's probably what you want, just store arbitrary data on the element

$("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') );
    });        
});  

这篇关于jQuery关键字"this"没有获得属性值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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