事件处理程序出错:“this.data()不是函数” [英] Error in event handler: "this.data() is not a function"
问题描述
我有一个链接的HTML列表,每个链接都带有 data- ...
属性:
I have an HTML list of links with data-…
attributes on each one:
<ul id="list">
<li><a data-info="link1"> **** </a></li>
<li><a data-info="link2">****</a></li>
<li><a data-info="link3">**** </a></li>
<li><a data-info="link4">****</a> </li>
</ul>
我需要收到 data-info
单击链接时的值。所以我想到这样的事情:
I need to receive the data-info
value of a link whenever it is clicked. So I thought something like this:
var my_links = $('#list').find('a');
my_links.on('click', function(){
console.log(this.data(info));
});
然后我得到:
Uncaught TypeError:this.data不是函数
Uncaught TypeError: this.data is not a function
如果我这样做:
var my_links = $('#list').find('a');
my_links.on('click', function(){
console.log(this);
});
我得到每个链接的完整HTML代码,例如:
I get the complete HTML code of each link, for example:
<a data-info="link1"> **** </a>
为什么会发生这两件事,我该如何解决?
Why are both things happening, and how can I fix it?
推荐答案
data()
是一个jQuery方法,而不是本机DOM对象的方法。
data()
is a jQuery method, not a method of native DOM objects.
此
将是< a>
元素被点击的 - 本机DOM对象( HTMLAnchorElement
)。给它一个jQuery包装器来调用jQuery方法:
this
will be the <a>
element that was clicked — a native DOM object (HTMLAnchorElement
). Give it a jQuery wrapper to call jQuery methods:
my_links.on('click', function() {
console.log( $(this).data('info') );
});
(并注意您没有 info
变量 - 您正在寻找字符串访问的数据 'info'
)
(and note that you don't have an info
variable - you're looking for the data accessed by the string 'info'
)
这篇关于事件处理程序出错:“this.data()不是函数”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!