javascript 事件处理程序中的错误:“this.data() 不是函数”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32212029/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 14:58:50  来源:igfitidea点击:

Error in event handler: "this.data() is not a function"

javascriptjquery

提问by Ornitier

I have an HTML list of links with data-…attributes on each one:

我有一个 HTML 链接列表,data-…每个链接都有属性:

<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>

I need to receive the data-infovalue of a link whenever it is clicked. So I thought something like this:

data-info每当单击链接时,我都需要接收链接的值。所以我想到了这样的事情:

var my_links = $('#list').find('a');

my_links.on('click', function(){
     console.log(this.data(info));
});

But then I get:

但后来我得到:

Uncaught TypeError: this.data is not a function

未捕获的类型错误:this.data 不是函数

If I just do:

如果我只是这样做:

var my_links = $('#list').find('a');

my_links.on('click', function(){
  console.log(this);
});

I get the complete HTML code of each link, for example:

我得到了每个链接的完整 HTML 代码,例如:

<a data-info="link1"> **** </a>

Why are both things happening, and how can I fix it?

为什么会发生这两件事,我该如何解决?

回答by Paul Roub

data()is a jQuery method, not a method of native DOM objects.

data()是一个 jQuery 方法,而不是原生 DOM 对象的方法。

thiswill be the <a>element that was clicked?—?a native DOM object (HTMLAnchorElement). Give it a jQuery wrapper to call jQuery methods:

this将是<a>被点击的元素?—?原生 DOM 对象 ( HTMLAnchorElement)。给它一个 jQuery 包装器来调用 jQuery 方法:

my_links.on('click', function() {
  console.log( $(this).data('info') );
});

(and note that you don't have an infovariable - you're looking for the data accessed by the string'info')

(请注意,您没有info变量 - 您正在寻找字符串访问的数据'info'

回答by robeau

Use $(this).data() instead of this.data().

使用 $(this).data() 而不是 this.data()。

var my_links = $('#list').find('a');
    my_links.on('click', function(){
        console.log($(this).data());
    });

Find more info on jQuery $(this) here: jQuery: What's the difference between '$(this)' and 'this'?

在此处查找有关 jQuery $(this) 的更多信息:jQuery:'$(this)' 和 'this' 之间有什么区别?