简体   繁体   中英

JQuery selector by data attribute when data is added dynamically?

I have a ul with several items. I populate the list dynamically after page load using jquery. As I add each list item, I also add an "itemID" to the data of that element using the jquery ".data()" function. Something like this:

var item = $('<li>My Item Name</li>');
item.data('itemID', '123ABC456');

Later, I need a selector to determine if there is any item in my item list with a specific itemID. First I tried using:

$('*[data-itemID="123ABC456"]');

This didn't work - and on further research, I discovered that this syntax only works if the data attribute was set in the DOM when the page was loaded; it doesn't work if you use the ".data" jquery method dynamically.

Next I tried:

$(':data(itemID==123ABC456)');

For some reason, this doesn't work. If I run simply $(':data(itemID)') , however, then I do get all the li elements that have an itemID in their data.

I know that the itemID attribute is set correctly, as when I call .data() on that list item I get:

Object { itemID="123ABC456"}

How can I select all elements that have an itemID of "123ABC456" in their data?

http://jsfiddle.net/w28p9/1/ <-- jsFiddle example showing differences with data-attribute & jquery.data()

jQuery.data() is different than HTML5 data-NAME attributes which you are trying to search for.

http://api.jquery.com/jQuery.data/

jQuery.data() saves inside of the jquery element (this data is hidden from plain sight). Looking for [data-itemID] would work if inside of the actual had: <li data-itemID="12345"></li> .

To retrieve and look for the actual hidden .data() try:

// of course be more specific than just searching through all <li>'s
$('li').each(function () {
    if ( $(this).data('itemID') === '123ABC456' ) {
        // do whatever you wanted to do with it
    } 
});

Hope that helps!

Instead of

$(item).data('itemID', '123ABC456')

use

$(item).attr('data-itemID', '123ABC456')

Then you can use

$('[data-itemID=123ABC456]') 

as a selector

如何将itemID放在DOM中:

var item = $('<li itemID="'+itemid+">My Item Name</li>');

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