Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/363.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/72.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript JQuery从单击函数中检索数据属性_Javascript_Jquery_Html_Typescript_Custom Data Attribute - Fatal编程技术网

Javascript JQuery从单击函数中检索数据属性

Javascript JQuery从单击函数中检索数据属性,javascript,jquery,html,typescript,custom-data-attribute,Javascript,Jquery,Html,Typescript,Custom Data Attribute,我有这样一个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-b

我有这样一个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>
但它总是提醒“未定义”

编辑:

我的断言从一开始就很糟糕,我使用的是Typescript语言中的lambda(或arrow)表达式。这使得关键字“this”的含义不同

片段:

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

工作正常。

您的HTML中没有
.barra
与原始
JS
-
$(“.barra.element”)
)元素,并且您没有正确编写回调:

$(".bar .element").on('click', function() {
    alert($(this).data('big'));
});
$(.bar.element”)。在('click',function()上{
警报($(this.data('big'));
});

加入我
耍我
转到列表
进入前10名

您应该像下面那样更改您的函数

$(".bar .element").on('click', function() {
    alert($(this).attr('data-big'));
});
您可以使用“id”来执行此操作:


加入我
以下是可行的解决方案:

jQuery:

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

在TypeScript中,箭头函数表达式(
()=>
)用于保留词法范围。这意味着当您在箭头函数内部使用
时,它将引用与在函数外部使用
相同的范围


在您的例子中,您希望函数在
onclick
事件的范围内运行,而不是在词法范围内运行,因此您应该避免使用arrow函数,而是使用
function()
.on('click',()=>
?)它是什么语法?您能确认jQuery的版本吗?@Wolf.on('click',()=>???它是什么样的语法?这是一种类型脚本语法,相当于.on('click',funtion(){});@a.Wolff它是一个@a.Wolff,如果有足够的浏览器支持它,它将是:)我不想在我的元素上添加ID我知道我的原始代码段有一个类选择器的输入错误,但问题并不存在。我的回调函数有一个错误的语法,我使用的是typescript lambda语法而不是通常的javascript语法。无论如何,我将您的标记为正确答案,因为您使用了JQuery“data”方法。
$(".bar .element").on('click', function() {
    alert($(this).attr('data-big'));
});