简体   繁体   English

如何通过.on方法访问JQuery HTML5数据属性?

[英]How to access JQuery HTML5 data attribute via the .on method?

This is my attempt to get the HTML5 data attribute named productId : 这是我尝试获取名为productId的HTML5数据属性:

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

I have several buttons with the class myButton , each with different productId's as their data. 我有几个按钮类myButton ,每个按钮都有不同的productId作为他们的数据。

But in this case, the code just look for the data from the body tag and not from the buttons with the class myButton . 但在这种情况下,代码只是查找body标签中数据,而不是来自myButton类的myButton

How can I specify the DOM element I want to extract the data? 如何指定要提取数据的DOM元素?

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: 使用jQuery直到1.4版本,数据属性不区分大小写,因此:

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

would be accessible with 可以访问

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

jQuery 1.5 and 1.6 jQuery 1.5和1.6

However, changes in jQuery 1.5 and 1.6 mean that data attributes are now forced to lowercase, so: 但是,jQuery 1.5和1.6中的更改意味着数据属性现在被强制为小写,因此:

<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. 虽然jQuery 1.5 and later版本中存在一个错误,但是我们无法升级jQuery版本。

Therefore, you should avoid using camel-cased data attributes in your HTML, and stick to all lowercase attributes such as 因此,您应该避免在HTML中使用camel-cased数据属性,并坚持使用所有小写属性,例如

<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'. 然后期望处理'productid'的.data()项目。

Try this: 尝试这个:

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

DEMO DEMO

maybe somethig like this ? 也许像这样的一些人?

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

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

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