2017-03-07 35 views
1

我有以下情況:如何使用jQuery對DOM元素執行重複的迭代操作?

var totalWidth = 0; 
$('.myclass').each(function() { 
    totalWidth += $(this).width(); 
}); 

現在我已經這樣做了之後,我想執行的每個單獨的$('.myclass')元素,例如,另一個動作

$('.myclass').each(function() { 
    // use computed totalWidth for something else 
}); 

我該怎麼做?第二次嘗試選擇元素會不會產生一些問題?

+0

你的意思是你想同時使用兩個'each'方法嗎?爲什麼這樣做? – Ionut

+1

不,它不會。只要這兩條語句是一個接一個的,它們就沒有任何關係。選擇或.each不會影響此類型的其他人。 –

+1

'第二次嘗試選擇元素是否會產生一些問題?'根本沒有,儘管可能有另一種方法來避免使用兩個循環。你可以顯示一小段HTML代碼,並說明你需要用'totalWidth'值來做什麼 –

回答

0

不,再次選擇元素不會產生任何問題,儘管它會花費一些不必要的時間搜索已經找到的元素。您可以通過使用鏈式.each來電防止這一點,就像這樣:

var totalWidth = 0; 
$('.myclass').each(function() { 
    totalWidth += $(this).width(); 
}).each(function() { 
    // use computed totalWidth for something else 
}); 

或者,如果你需要做兩環之間的一些中間業務,可以存儲jQuery的集合中的變量:

var totalWidth = 0; 
var $myclass = $('.myclass').each(function() { 
    totalWidth += $(this).width(); 
}); 
// do other stuff 
$myclass.each(function() { 
    // use computed totalWidth for something else 
}); 
+0

謝謝!究竟是什麼意見在問題上說。 – george

相關問題