简体   繁体   中英

Using HTML5 Data Attribute in jQuery Selector

Noob Question on Data Attribute

I was wondering will using data-attribute in jQuery Selector can bring any trouble in the future?

I'm trying to reduced the usage of .class and #id as jQuery Selector, since most of data I'm working on will generated from data-attribute

example of the code

$(document).ready(function(){

  var mydata = $(document).data('my-data-attribute');

});

will the code above slowing the load time?

or

$('[data-suffix-attribute="some_value"]').each(function(){
   ......
});

or

$('[data-suffix-attribute="delete"]').click(function(){
   // delete action happening here
});

will this bring trouble?

$(document).ready(function(){

  var mydata = $(document).data('my-data-attribute');

});

The code above will not work. If you want to read the HTML5 data attribute of an element using the jQuery .data() method firstly you need to select the relevant element using a jQuery selector and then you can use the method as is shown below:

var mydata = $('.example').data('suffix');

This will read the value of the data-suffix attribute of an element with a class of "example".

The other important thing to note when using the .data() method is that you have to omit the data- prefix from the selector to read the value stored in that attribute.

The way you have selected the attribute before the .each() method will work:

$('[data-suffix-attribute="some_value"]');

However, it would be better if you can narrow it down to a specific element like:

$('div[data-suffix-attribute="some_value"]');

This is because the first selector will go through every node in the document which will take more time whereas the second will only go through the div tags in the document.

The attribute selector is supported by the native query selectors so it is fine. As far as future is concerned I don't think in near future it will be a problem.

But it will be better if you can use a element selector attached to the attribute selector like $('div[data-suffix-attribute="delete"]')

If you are very worried about performance it will be a better choice to add a class attribute to the desired elements and then use class selector

It would be better to use id in selector which is fast obviously, If you have multiple data attributes then it is better to use $('[data-suffix-attribute="delete"]').click(); . Instead of this you can use the parent selector for your data-attribute elements like,

$('#parentId').on('click','[data-suffix-attribute="delete"]',function(){
   // delete action happening here
});

#parentId contains all data attribute elements

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