javascript - jQuery 关键字 "this"取不到属性值

标签 javascript jquery html this

我正在使用 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 作为警告消息。

我可以调用关键字“this”的 id(使用 this.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') );
    });        
});  

关于javascript - jQuery 关键字 "this"取不到属性值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29188340/

相关文章:

使用 php 变量作为 id 的 javascript 切换函数

javascript - onClick触发点击报错: current.点击不是函数

任意编号 li 的 JavaScript

php - 在 jQuery 中设置?

javascript - 更改图像属性时如何使用 jquery 获得平滑效果?

javascript - 未捕获的类型错误 : Object #<AbstractAjaxReq> has no method 'getAjaxResponse'

javascript - 6 个网格 DIV,每个带有 2 个内容 DIV 和切换功能

javascript - 如何避免在popstate事件处理程序中调用history.pushState?

css - 固定左右栏,液体中间无法跨越整个页面

javascript - 提交时在本地保存表单更改