[英]jquery data-id not working as expected
I was just trying to get data-id of an html element by refering the previously solved issue in stackoverflow.I am exactly trying the same but getting undefined.Why is it so? 我只是想通过引用之前在stackoverflow中解决的问题来获取html元素的data-id,我正在尝试相同的操作,但是却变得不确定,为什么呢?
<!DOCTYPE html> <html> <head> <title></title> </head> <body> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <a data-id="123" class="a">link</a> <script type="text/javascript"> $(document).ready(() => { $('.a').on('click',() => { console.log($(this).attr("data-id")); }) }) </script> </body> </html>
You are using ES6 by using () =>
Arrow Function thats why not working your code. 您通过使用
() =>
Arrow Function使用ES6,这就是为什么不使用代码的原因。 It's the specific functionality you're asking for by using () => {}
instead of function () { }
: 这是您通过使用
() => {}
而不是function () { }
所要求的特定功能:
<script type="text/javascript">
$(document).ready(() => {
$('.a').on('click', function() {
console.log($(this).data('id'));
});
})
</script>
The way to solve this particular problem is not to use this to gain access to the clicked element, but instead use event.currentTarget
: 解决此特定问题的方法不是使用它来访问clicked元素,而是使用
event.currentTarget
:
<script type="text/javascript">
$(document).ready(() => {
$('.a').on('click', (e) => {
console.log($(e.currentTarget).data('id'));
});
})
</script>
I suggest you to read this documentation Arrow_functions 我建议您阅读本文档Arrow_functions
Try this Your created function was wrong. 尝试此操作您创建的函数错误。
$('a').click(function(){
console.log($(this).data('id'));
})
OR 要么
$('a').on('click',function(){
console.log($(this).attr('data-id'));
})
Try this: 尝试这个:
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a data-id="123" class="a">link</a>
<script type="text/javascript">
$(document).ready(() => {
$('.a').on('click',function() {
console.log($(this).data("id"));
})
})
</script>
</body>
</html>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.