简体   繁体   English

JQuery从点击功能中回溯数据属性

[英]JQuery Retrive data-attribute from on click function

I have a div structure like this: 我有这样的div结构:

<div class='bar'>
    <div class='contents'>
        <div class='element' data-big='join'>JOIN ME</div>
        <div class='element' data-big='play'>PLAY ME</div>
        <div class='element' data-big='list'>GO TO LIST</div>
        <div class='element' data-big='chart'>GO TO TOP 10</div>
    </div>
</div>

How can I refer to their data attribute by onClick function? 如何通过onClick函数引用其数据属性?

I tried with 我试过了

$(".bar .element").on('click', ()=> {
    alert($(this).data('big'));
});

But it always alert "undefined". 但它始终警告“未定义”。

EDIT: 编辑:

My assertion was bad from the beginning, I was using a lambda (or arrow) expression from the Typescript language. 我的断言从一开始就很糟糕,我使用了Typescript语言中的lambda(或箭头)表达式。 That makes the different meaning of the keyword "this". 这使得关键字“this”的含义不同。

the snippet: 片段:

$(".bar .element").on('click', function(){
    alert($(this).data('big'));
});

works as espected. 工作得到尊重。

You do not have a .barra ( as you had in your original JS -- $(".barra .element") ) element in your HTML and you've not written the callback properly: 你的.barra没有.barra就像你原来的JS - $(".barra .element") )元素一样,你没有正确编写回调函数:

$(".bar .element").on('click', function() {
    alert($(this).data('big'));
});

  $(".bar .element").on('click', function() { alert($(this).data('big')); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class='bar'> <div class='contents'> <div class='element' data-big='join'>JOIN ME</div> <div class='element' data-big='play'>PLAY ME</div> <div class='element' data-big='list'>GO TO LIST</div> <div class='element' data-big='chart'>GO TO TOP 10</div> </div> </div> 

you should change your function like below 你应该改变你的功能,如下所示

$(".bar .element").on('click', function() {
    alert($(this).attr('data-big'));
});

In TypeScript, the arrow function expression ( () => ) is used to preserve the lexical scope. 在TypeScript中,箭头函数表达式( () => )用于保留词法范围。 This means that when you use this inside of an arrow function, it will refer to the same scope as using this outside of the function. 这意味着,当你使用this箭头的功能里面,它会指向同一个范围,因为使用this功能之外。

In your case, you want the function to run with the scope of the onclick event, not the lexical scope, so you should avoid using the arrow function and instead use function () . 在您的情况下,您希望函数使用onclick事件的范围而不是词法范围运行,因此您应该避免使用箭头函数而是使用function ()

Here is the working solution: 这是工作解决方案:

jQuery: jQuery的:

$(".bar .element").on('click', function() {
    alert($(this).attr('data-big'));
});

DEMO DEMO

you can use "id" to do it: 你可以使用“id”来做到这一点:

 <div id='div1' class='element' data-big='join'>JOIN ME</div> 

 $("#div1").on('click', ()=> { alert($(this).data('big')); }); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM