jQuery how to find an element based on a data
I've got the following scenario:
var el = 'li';
and there are 5 <li>
's on the page each with a data-slide=number
attribute (number being 1,2,3,4,5 respectively).
I now need to find the currently active slide number which is mapped to var current = $('ul').data(current);
and is updated on each slide change.
So far my tries have been unsuccessful, trying to construct the selector that would match the current slide:
$('ul').find(el+[data-slide=+current+]);
does not match/return anything…
The reason I can't hardcode the li
part is that this is a user accessible variable that can be changed to a different element if required, so it may not always be an li
.
Any ideas on what I'm missing?
You have to inject the value of current
into an Attribute Equals selector:
$("ul").find(`[data-slide='${current}']`)
For older JavaScript environments (ES5 and earlier):
$("ul").find("[data-slide='" + current + "']");
in case you don't want to type all that, here's a shorter way to query by data attribute:
$("ul[data-slide='" + current +"']");
FYI: http://james.padolsey.com/javascript/a-better-data-selector-for-jquery/
When searching with [data-x=...], watch out, it doesn't work with jQuery.data(..) setter :
$('<b data-x="1">' ).is('[data-x=1]') // this works
> true
$('<b>').data('x', 1).is('[data-x=1]') // this doesn't
> false
$('<b>').attr('data-x', 1).is('[data-x=1]') // this is the workaround
> true
You can use this instead:
$.fn.filterByData = function(prop, val) {
return this.filter(
function() { return $(this).data(prop)==val; }
);
}
$('<b>').data('x', 1).filterByData('x', 1).length
> 1
链接地址: http://www.djcxy.com/p/22952.html
上一篇: 类库和框架有什么区别
下一篇: jQuery如何根据数据查找元素