2012-05-30 13 views
0

我在這裏有一個函數,循環兩個包裝,然後通過它的各自的孩子循環,並引發它一個數字列出的項目按數字順序。我沒有使用for循環,而是決定使用每個jQuery函數。這裏是我的問題:當兩者都實現相同的事情時,編寫此代碼的首選方式是什麼?

哪種方式是更好地實現這一目標,什麼是轉到一個這樣或那樣的優勢/劣勢?使用for循環更好嗎?

此:

$(".articleContentWrapper").each(function() { 
    var i = 1; 
    $(this).find(".howToStepNumber").each(function() { 
     var b = i++; 
     $(this).html(b); 
    }); 
}); 

或者這樣:

$(".articleContentWrapper").each(function() { 
    var i = 1; 
    $(this).find(".howToStepNumber").each(function() { 
     $(this).html(i++); 
    }); 
}); 
+0

有到變種'B = ++沒有優勢; $(本)。html的(B);'。你只是在浪費記憶。 – lanzz

回答

4

這個怎麼樣?

$(".articleContentWrapper").each(function() { 
    $(this).find(".howToStepNumber").each(function (i, e) { 
     $(this).html(i + 1); 
    }); 
}); 

.each()方法已經提供了一個索引持有者,所以你不需要自己創建一個。

+1

在OP代碼中'i'從1開始:P –

+0

'.each'中傳遞的'e'是什麼? – Sethen

+1

這是索引的DOM元素。所以你也可以編寫'$(e).html(i + 1);'而不是'$(this).html(i + 1);' –

0

,我可能會寫爲:

$(".articleContentWrapper").each(function() { 
    $(".howToStepNumber", this).each(function (i) { 
     $(this).html(i); // or i+1 depending on what you want 
    }); 
}); 

的發現真的是沒有必要要麼,使語句更長。

1

嘗試像下面,

$(".howToStepNumber", $(".articleContentWrapper")).html(function() { 
    return $(this).index() + 1; 
}); 

DEMO

+0

我真的很喜歡這個。一個不錯的方法。 –

+0

我從來沒有見過它寫成像'$(「。howToStepNumber」,$(「。articleContentWrapper」))'這是如何工作的? – Sethen

+1

它等同於'$( 「articleContentWrapper」)。找到( '.howToStepNumber')' –

相關問題