将增量类添加到div内的图像

时间:2012-03-02 08:04:13

标签: javascript jquery

好吧,我认为还没有人覆盖过这个。

我有一个div里面有x个图像。我需要将类00x添加到x从1开始的每个图像,并且每次为每个图像上升。我尝试用for in语句做这个,​​但似乎无法使它工作。我正在使用jquery库,所以随时建议jQuery相关的修复程序。这是我的HTML:

<div id="fixed">
    <img src="/prodimages/Ad060-2.jpg" />
    <img src="/prodimages/Ad060-2.jpg" />
    <img src="/prodimages/Ad060-2.jpg" />
</div>

所以我需要它来选择#fixed里面的所有图像,然后为每个图像添加00 + i类,其中i ++。我需要像php foreach这样的东西。我真的不明白在工作中如何。

请指教。 :)

3 个答案:

答案 0 :(得分:5)

如果图像数量超过10,请使用以下内容:

function pad_number(num) {
   if(num < 10) return '00' + num;
   else if (num < 100) return '0' + num;
   return num;
}

jQuery('#fixed img').each(function(index, el) {
   jQuery(el).addClass(pad_number(index));
});

答案 1 :(得分:1)

这样的事情应该这样做:

$("#fixed img").each(function(i) {
   $(this).addClass("00" + i);
};

答案 2 :(得分:0)

$("#fixed img").each(function(i){
  this.addClass($.strPad(i,3));
});

$.strPad = function(i,l,s) {
    var o = i.toString();
    if (!s) { s = '0'; }
    while (o.length < l) {
        o = s + o;
    }
    return o;
};

源填充功能:http://stv.whtly.com/2009/02/27/simple-jquery-string-padding-function/

我希望这会有所帮助:)