简体   繁体   中英

How do I get certain values of a HTML attribute in Javascript?

I would like to take the value of an attribute, process it and then replace a PHP variable with the value we receive at the end.

The data attribute is data-id , all I need assistance with is getting the value of data-id into Javascript on a click event , the rest I can do.

An example:

Person clicks an tag with the data-id set as, say, 7. I'd then need to extract that 7 from the HTML code and into a Javascript variable so I can work with said value.

I hope this is clear enough

This will do the trick.

$(selector).click(function(){
    var dataAttrId = $(this).attr('data-id');
    // Your code goes here...
});

Try this

$('#someelement').click(function(){
    $(this).data('id');
});

Use this

jQuery('your id or class or element').click(function(){
    var mainData= jQuery('your id or class or element').attr('data-id');
alert(mainData);
});

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