jQuery 如何根据数据属性值查找元素? [英] jQuery how to find an element based on a data-attribute value?
问题描述
我有以下场景:
var el = 'li';
页面上有 5 个 ,每个都有一个
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?
推荐答案
你必须将 current
的值注入到 属性等于选择器:
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屋!