我正在使用 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/