Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
375 views
in Technique[技术] by (71.8m points)

jquery - jQuery如何根据数据属性值查找元素?(jQuery how to find an element based on a data-attribute value?)

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) .

(页面上有5个<li> ,每个都有一个data-slide=number属性(数字分别为1,2,3,4,5) 。)

I now need to find the currently active slide number which is mapped to var current = $('ul').data(current);

(我现在需要找到当前活动的幻灯片编号,该编号映射到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 .

(我无法对li部分进行硬编码的原因是,这是一个用户可访问的变量,如果需要可以更改为不同的元素,因此它可能并不总是一个li 。)

Any ideas on what I'm missing?

(关于我缺少的任何想法?)

  ask by Jannis translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You have to inject the value of current into an Attribute Equals selector:

(您必须将current的值注入Attribute Equals选择器:)

$("ul").find(`[data-slide='${current}']`)

For older JavaScript environments (ES5 and earlier):

(对于较旧的JavaScript环境(ES5及更早版本):)

$("ul").find("[data-slide='" + current + "']"); 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.8k users

...