使用$ .each将addClass添加到元素 [英] using $.each to addClass to elements
问题描述
我正在尝试使用数组设置锚子集的样式
I'm trying to style a sub-set of anchors using an array
HTML& CSS:
HTML & CSS:
<div>
<a href="#1">one</a>
<a href="#2">two</a>
<a href="#3">three</a>
<a href="#4">four</a>
<a href="#5">five</a>
<a href="#6">six</a>
<a href="#7">seven</a>
</div>
.hilight {
background: #f00;
}
例如我如何将类别"hilight"添加到锚点2、5和6 ...
e.g. how would I add the class 'hilight' to anchors 2, 5, & 6...
已对此进行了测试:
$("a[href='#5']").addClass('hilite');
我用$ .each()尝试了以下操作,但这不起作用.我想我要遍历每个锚3次,但是我没想到没有输出!
I tried the the following with $.each(), which doesn't work. I guess I'm iterating over each anchor 3 times, but I didn't expect NO output!
var arr = ["#2", "#5", "#6"];
$.each(arr, function(index, value) {
$("a[href=value]").addClass('hilite');'
});
有人可以指出正确的方向吗:)
Can someone point me in the right direction please :)
推荐答案
您的代码不起作用,因为$("a[href=value]")
不存在.
Your code doesn't work because $("a[href=value]")
doesn't exist.
您想使用$("a[href='"+value+"']")
代替,其中value将被变量值的值替换".
You wan to use $("a[href='"+value+"']")
instead, where value will be "replace" by the value of the variable value.
这里解决:
var arr = ["#2", "#5", "#6"];
$.each(arr, function(index, value) {
$("a[href='"+value+"']").addClass('hilite');
});
这篇关于使用$ .each将addClass添加到元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!