jQuery 如何根据数据属性值查找元素?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4191386/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery how to find an element based on a data-attribute value?
提问by Jannis
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).
<li>
页面上有 5 个,每个都有一个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);
and is updated on each slide change.
我现在需要找到当前活动的幻灯片编号,该编号映射到var current = $('ul').data(current);
并在每次幻灯片更改时更新。
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?
关于我缺少什么的任何想法?
回答by Frédéric Hamidi
You have to inject the value of current
into an Attribute Equalsselector:
您必须将 的值注入current
到Attribute Equals选择器中:
$("ul").find(`[data-slide='${current}']`)
For older JavaScript environments (ES5and earlier):
对于较旧的 JavaScript 环境(ES5及更早版本):
$("ul").find("[data-slide='" + current + "']");
回答by KevinDeus
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/
仅供参考:http: //james.padolsey.com/javascript/a-better-data-selector-for-jquery/
回答by psycho brm
When searching with [data-x=...], watch out, it doesn't work with jQuery.data(..) setter:
使用 [data-x=...] 搜索时,请注意,它不适用于 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
回答by bPratik
I improved upon psycho brm's filterByData extensionto jQuery.
我改进了psycho brm对jQuery的filterByData 扩展。
Where the former extension searched on a key-value pair, with this extension you can additionally search for the presence of a data attribute, irrespective of its value.
前一个扩展在键值对上搜索,使用此扩展,您可以额外搜索数据属性的存在,而不管其值如何。
(function ($) {
$.fn.filterByData = function (prop, val) {
var $self = this;
if (typeof val === 'undefined') {
return $self.filter(
function () { return typeof $(this).data(prop) !== 'undefined'; }
);
}
return $self.filter(
function () { return $(this).data(prop) == val; }
);
};
})(window.jQuery);
Usage:
用法:
$('<b>').data('x', 1).filterByData('x', 1).length // output: 1
$('<b>').data('x', 1).filterByData('x').length // output: 1
// test data
function extractData() {
log('data-prop=val ...... ' + $('div').filterByData('prop', 'val').length);
log('data-prop .......... ' + $('div').filterByData('prop').length);
log('data-random ........ ' + $('div').filterByData('random').length);
log('data-test .......... ' + $('div').filterByData('test').length);
log('data-test=anyval ... ' + $('div').filterByData('test', 'anyval').length);
}
$(document).ready(function() {
$('#b5').data('test', 'anyval');
});
// the actual extension
(function($) {
$.fn.filterByData = function(prop, val) {
var $self = this;
if (typeof val === 'undefined') {
return $self.filter(
function() {
return typeof $(this).data(prop) !== 'undefined';
});
}
return $self.filter(
function() {
return $(this).data(prop) == val;
});
};
})(window.jQuery);
//just to quickly log
function log(txt) {
if (window.console && console.log) {
console.log(txt);
//} else {
// alert('You need a console to check the results');
}
$("#result").append(txt + "<br />");
}
#bPratik {
font-family: monospace;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="bPratik">
<h2>Setup</h2>
<div id="b1" data-prop="val">Data added inline :: data-prop="val"</div>
<div id="b2" data-prop="val">Data added inline :: data-prop="val"</div>
<div id="b3" data-prop="diffval">Data added inline :: data-prop="diffval"</div>
<div id="b4" data-test="val">Data added inline :: data-test="val"</div>
<div id="b5">Data will be added via jQuery</div>
<h2>Output</h2>
<div id="result"></div>
<hr />
<button onclick="extractData()">Reveal</button>
</div>
Or the fiddle: http://jsfiddle.net/PTqmE/46/
或者小提琴:http: //jsfiddle.net/PTqmE/46/
回答by rap-2-h
Without JQuery, ES6
没有 JQuery,ES6
document.querySelectorAll(`[data-slide='${current}']`);
I know the question is about JQuery, but readers may want a pure JS method.
我知道这个问题是关于 JQuery 的,但读者可能想要一个纯 JS 方法。
回答by user1378423
I have faced the same issue while fetching elements using jQuery and data-* attribute.
我在使用 jQuery 和 data-* 属性获取元素时遇到了同样的问题。
so for your reference the shortest code is here:
所以供您参考,最短的代码在这里:
This is my HTML Code:
这是我的 HTML 代码:
<section data-js="carousel"></section>
<section></section>
<section></section>
<section data-js="carousel"></section>
This is my jQuery selector:
这是我的 jQuery 选择器:
$('section[data-js="carousel"]');
// this will return array of the section elements which has data-js="carousel" attribute.
回答by Jomin George Paul
$("ul").find("li[data-slide='" + current + "']");
I hope this may work better
我希望这可能会更好
thanks
谢谢
回答by Matas Vaitkevicius
This selector $("ul [data-slide='" + current +"']");
will work for following structure:
此选择器$("ul [data-slide='" + current +"']");
适用于以下结构:
<ul><li data-slide="item"></li></ul>
While this $("ul[data-slide='" + current +"']");
will work for:
虽然这$("ul[data-slide='" + current +"']");
将适用于:
<ul data-slide="item"><li></li></ul>
<ul data-slide="item"><li></li></ul>
回答by Bryan Garaventa
Going back to his original question, about how to make this work without knowing the element type in advance, the following does this:
回到他最初的问题,关于如何在事先不知道元素类型的情况下进行这项工作,以下是这样做的:
$(ContainerNode).find(el.nodeName + "[data-slide='" + current + "']");