如何使用数据属性作为变量来定位元素? [英] How to target element with data attribute as a variable?
本文介绍了如何使用数据属性作为变量来定位元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在这样做,但是没有用
I am doing this but it's not working
html
<a href="#filter-year-y2013" data-filter-value=".y2013">2013</a>
jquery
var token = document.location.href.split('=')[1];
var attribu = "." + token;
$('a[data-filter-value= attribu]').css("background", "#ddd");
该问题与与其他问题不同,因为我没有要求定位任何选择器带有变量但具有数据属性
This question is different from this other question as I am not asking to target any selector with variable but a data attribute
推荐答案
您需要将变量与字符串选择器连接在一起,请尝试以下操作:
You need to concatenate the variable together with the string selector, try this:
$('a[data-filter-value="' + attribu + '"]').css("background", "#ddd");
或者,您可以避免串联并使用filter()
:
Alternatively you could avoid the concatenation and use filter()
:
$('a').filter(function() {
return $(this).data('filter-value') == attribu;
}).css("background", "#ddd");
这篇关于如何使用数据属性作为变量来定位元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文