简体   繁体   中英

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?

 <!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. It's the specific functionality you're asking for by using () => {} instead of 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 :

<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

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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