简体   繁体   中英

Extract attribute from DOM element with jQuery

Here's a code that I have

    <button data-id="123">
        Restore
    </button>
    function aButtonPressed(id){
        alert(id);
    }
    $(document).ready(function() {
        $('button').on('click', function(){aButtonPressed(data-id);});
    });

I want the function to show in alert box string "123". How should I extract the data-id ?

Change to this

$('button').on('click', function(){
alert($(this).data('id'));
})

尝试这个

  $('button').on('click', function(){aButtonPressed($(this).attr('data-id'));});

use dataset property : https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/dataset

var btn = document.querySelector('button');

btn.onclick = function(){
      console.log(btn.dataset.id);
};

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