0

这段代码真的把我搞砸了..你能帮忙吗?有 5 个元素,带有#newlinks. 总之#newlinks,是有孩子的a。这段代码在第一个上运行完美#newlinks,但在那之后,它不会给偶数a元素一个灰色背景。 #newlinks.

$(function(){
    var bg  = 0;
    $("#newlinks").children("a").each(function(){
        if(bg % 2 == 0){
            $(this).css("backgroundColor", "#F2F2F2");
            bg++;
        }else{
            bg++;
        }
    });
});

我也试过这个,但我想它不会起作用,因为$(this)可能既选择了 newlinks-element 又选择了 a-element。

$(function(){
    var bg  = 0;
    $("#newlinks").each(function(){
        $(this).children("a").each(function(){
            if(bg % 2 == 0){
                $(this).css("backgroundColor", "#F2F2F2");
                bg++;
            }else{
                bg++;
            }
        });
    });
});
4

3 回答 3

3

您不能为多个元素提供相同的 ID。它们必须是唯一的。

你必须使用类。所以那个$(".newlinks")选择器应该可以工作。

于 2013-06-02T10:12:43.660 回答
2

ID 每页应该只有一个。请更改为类<div class="newlinks">,然后使用以下代码:

$(function(){
  $(".newlinks").children("a").each(function(index){
        if(index % 2 == 0){
            $(this).css("background", "#000000");
        }
    });
});
于 2013-06-02T10:17:50.890 回答
2

试试这个jssfiddle

$(function () {
    $("#newlinks a").each(function (index) {
        if (index % 2 == 0) {
            $(this).css("backgroundColor", "#F2F2F2");
        }
    });
});
于 2013-06-02T11:24:25.590 回答