繁体   English   中英

jQuery的数据ID无法正常工作

[英]jquery data-id not working as expected

我只是想通过引用之前在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> 

您通过使用() => Arrow Function使用ES6,这就是为什么不使用代码的原因。 这是您通过使用() => {}而不是function () { }所要求的特定功能:

<script type="text/javascript">
  $(document).ready(() => {
    $('.a').on('click', function() {
      console.log($(this).data('id'));
    });

  })
</script>

解决此特定问题的方法不是使用它来访问clicked元素,而是使用event.currentTarget

<script type="text/javascript">
  $(document).ready(() => {
    $('.a').on('click', (e) => {
      console.log($(e.currentTarget).data('id'));
    });
  })
</script>

我建议您阅读本文档Arrow_functions

尝试此操作您创建的函数错误。

$('a').click(function(){
    console.log($(this).data('id'));
})

要么

$('a').on('click',function(){
    console.log($(this).attr('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',function() {
                console.log($(this).data("id"));
            })

        })
    </script>
</body>
</html>

暂无
暂无

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

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