문제

This is my attempt to get the HTML data attribute named productId:

$('body').on("click", '.myButton', function () {
    var productId = (this).dataset.productId;
});

I have several buttons with the class myButton, each with different productIds as their data.

But in this case, the code just look for the data from the body tag and not from the buttons with the class myButton.

How can I specify the DOM element I want to extract the data?

Ideally this should work for me in the first place, but for some reason it isn't:

 $('.myButton').on("click", null, function () {
        var productId = (this).dataset.productId;
 });
도움이 되었습니까?

해결책

Using jQuery up to and including version 1.4, data attributes were case insensitive, therefore:

<input type="button" class="myButton" value="click me" data-productId="abc"/>

would be accessible with

$('.myButton').data('productId');​

jQuery 1.5 and 1.6

However, changes in jQuery 1.5 and 1.6 mean that data attributes are now forced to lowercase, so:

<input type="button" class="myButton" value="click me" data-productId="abc"/>

is only accessible with

$('.myButton').data('productid');​

Although there is a bug in jQuery 1.5 and later that prevents us from upgrading the version of jQuery.

Therefore, you should avoid using camel-cased data attributes in your HTML, and stick to all lowercase attributes such as

<input type="button" class="myButton" value="click me" data-productid="abc"/>

or use dashed attributes such as

<input type="button" class="myButton" value="click me" data-product-id="abc"/>

and then expect to deal with .data() items of 'productid'.

Try this:

$('body').on("click", '.myButton', function() {
    var productId = $(this).attr('data-productId');
    alert(productId);
});

DEMO

다른 팁

maybe somethig like this ?

  $('body').on("click", '.myButton', function () {
       var productId = $(this).data("productId");
  });
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top