jQuery如何根据数据属性值查找元素? [英] jQuery how to find an element based on a data-attribute value?
问题描述
我有以下情况:
var el = 'li';
,页面上有5个<li>
,每个都有data-slide=number
属性(数字分别为1,2,3,4,5).
and there are 5 <li>
's on the page each with a data-slide=number
attribute (number being 1,2,3,4,5 respectively).
我现在需要找到当前活动的幻灯片编号,该编号已映射到var current = $('ul').data(current);
,并且在每次更改幻灯片时都会更新.
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…
我无法对li
部分进行硬编码的原因是,这是一个用户可访问的变量,可以根据需要将其更改为其他元素,因此它不一定总是li
.
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}']`)
对于较旧的JavaScript环境(ES5和更早版本):
For older JavaScript environments (ES5 and earlier):
$("ul").find("[data-slide='" + current + "']");
这篇关于jQuery如何根据数据属性值查找元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!