开发者

jquery css3 question

Is there a way to write this more elegantly??

$("li.list_restaurant_item:nth-child(1)").css("background-color", "#FBE9E7");
$("li.list_restaurant_item:nth-child(1)").css("padding", "4px");
$("li.list_restaurant_item:nth-child(2)").css("background-color", "#FBE9E7");
$("li.list_restaurant_item:nth-child(2)").css("padding", "4px");
$("li.list_restaurant_item:nth-child(3)").css("background-color", "#FBE9E7");
$("li.list_restaurant_item:nth-child(3)").css(开发者_开发百科"padding", "4px");


I'd go:

$("li.list_restaurant_item:nth-child(1)").addClass('someClass')

That way you can get all of the CSS out of your JS.


you can write:

$("li.list_restaurant_item").slice(0, 3).css({"background-color": "#FBE9E7", "padding": "4px");


At the very least, you can avoid the redundant lookups:

$("li.list_restaurant_item:nth-child(1), li.list_restaurant_item:nth-child(2), li.list_restaurant_item:nth-child(3)").css({
    "background-color": "#FBE9E7",
    "padding", "4px"
});

Or depending on your markup, the :lt selector might do it:

$("li.list_restaurant_item:lt(3)").css({
    "background-color": "#FBE9E7",
    "padding", "4px"
});

Note that unlike :nth-child, :lt indexes are 0-based, and so the above matches the first three items (0, 1, and 2).


The entire scope of the task at hand it note specifically clear, but you could make this clearer by creating a style and adding / removing that as necessary.

Create a re-usable style:

.MyStyleClass { background-color:#FBE9E7; padding:4px; }

Add the class as required, per item:

$("li.list_restaurant_item:nth-child(1)").addClass("MyStyleClass");
$("li.list_restaurant_item:nth-child(2)").addClass("MyStyleClass");
$("li.list_restaurant_item:nth-child(3)").addClass("MyStyleClass");

If this is to be done for all items in the list, then you could possibly use the each method on the list element. Something like this might do the trick:

$.each($("li.list_restaurant_item").children(), function () {
    $(this).addClass("MyStyleClass");
});
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜