开发者

Adding icons to many li elements

开发者 https://www.devze.com 2023-03-13 17:25 出处:网络
Whats the most efficient way to add different icons to a large number of li elements. right now I\'m using a separate class for now but its kind of redundant to have all theses css classes.

Whats the most efficient way to add different icons to a large number of li elements. right now I'm using a separate class for now but its kind of redundant to have all theses css classes.

I'm thinking the only way to do this is using javascript jquery. Is this 开发者_如何学Pythonthe only way, as css has no looping ability, or not that I know about.


Classes are the most efficient way to add different icons to many li elements.

Remember to keep all icons in one file. That, plus some web-based sprites generators should save you some work.

Doing that in JavaScript would affect page load speed and overall user experience.


What you could do is put all your icons into a single image, and have all the li elements belong to a class that uses that large image as the background. Then simply specify the background offset for each li.

This is a technique known as a sprite sheet - for more info read AListApart:Sprites


You can use jQuery to loop through all of the li elements in your page, and perform some action (this example prepends an image to each element):

$("li").each(function() {
    $(this).prepend("<img src='random.png' />");
});

However, if you need to add a different image to each element, I don't see how looping through them all is going to help you. If that's the case, what's wrong with your current method of using a long list of CSS classes?

Update Based on your comment, you could get the index of each li element and use it in the src attribute when adding the image:

$("li").each(function() {
    var index = $(this).index();
    $(this).prepend("<img src='random" + index + ".png' />");
});
0

精彩评论

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