开发者

using $.each to addClass to elements

I'm trying to style a sub-set of anchors using an array

HTML & CSS:

<div>
    <a href="#1">one</a>
    <a href="#2">two</a>开发者_C百科;
    <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;
}

e.g. how would I add the class 'hilight' to anchors 2, 5, & 6...

Having tested this:

$("a[href='#5']").addClass('hilite');

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


You dont need each at all, you can just use all selectors separated by commas.

$("a[href='#2'], a[href='#5'], a[href='#6']").addClass('hilite');


Your code doesn't work because $("a[href=value]") doesn't exist.

You wan to use $("a[href='"+value+"']") instead, where value will be "replace" by the value of the variable value.

Here a fix:

var arr = ["#2", "#5", "#6"];   
$.each(arr, function(index, value) {
    $("a[href='"+value+"']").addClass('hilite');
});


If you don't have a TON of them, it might be simpler to just do...

$("a[href='#2'], a[href='#5'], a[href='#6']").addClass('hilite');

To do the same thing, but more dynamically (for John)...

var arr = ["#2", "#5", "#6"]; 
$("a[href='"+arr.join("'], a[href='")+"']").addClass('hilite');

This assumes that arr always has at least one element.


The jQuery addClass() method has the ability to create a function to determine what class to add. You can use this to determine if the element is a one that needs the class added. This would be more efficient than running the selector $("a[href='"+value+"']") for each value in the array as it would only traverse the DOM once instead of n(size of the array) times.

var arr = ["#2", "#5", "#6"];  

$("a").addClass(function () {
  if (arr.indexOf($(this).attr("href")) != -1) {
    return "hilight";
  }
});

Here is a demonstration http://jsfiddle.net/VqLnt/3/

I also want to note that your CSS class is named hilight but the class you are trying to add in JavaScript is hilite. This is probably a typo but just want you to be aware.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜