2013-04-02 22 views
1

我有一個HTML結構如下所示:jQuery的定位和移動特定元素逐個

<tr class="v65-productDisplay-row"></tr> 
<tr class="v65-productDisplay-row PriceAndButton"></tr> 
<tr class="v65-productDisplay-row PhotoLine"></tr> 
<tr class="v65-productDisplay-row"></tr> 
<tr></tr> 
<tr class="v65-productDisplay-row"></tr> 
<tr class="v65-productDisplay-row PriceAndButton"></tr> 
<tr class="v65-productDisplay-row PhotoLine"></tr> 
<tr class="v65-productDisplay-row"></tr> 
<tr></tr> 
<tr class="v65-productDisplay-row"></tr> 
<tr class="v65-productDisplay-row PriceAndButton"></tr> 
<tr class="v65-productDisplay-row PhotoLine"></tr> 
<tr class="v65-productDisplay-row"></tr> 
<tr></tr> 
...and so on 

我試圖定位每個PriceAndButton TR和每一對應的PhotoLine TR之後將其插入。下面是代碼我有這麼遠,但它不工作作爲尚未:

 jQuery(".PriceAndButton").each(function() { 
      var IndexValue = $(this).index(); 
      $(this).insertAfter(".PhotoLine:eq(" + IndexValue + 1 + ""); 
     }); 

我的想法是讓每個PriceAndButton元素的索引值和PhotoLine TR那裏的EQ等於指標值後插入+ 1.這應該是正確的,因爲PhotoLine TR總是緊隨其後?

回答

1

你的代碼(我固定在右括號):

".PhotoLine:eq(" + IndexValue + 1 + ")"; 

將串聯爲一個字符串。如果IndexValue等於3,那麼您將得到字符串.PhotoLine:eq(31)而不是.PhotoLine:eq(4)。你的意思是:

".PhotoLine:eq(" + (IndexValue + 1) + ")"; 

但即使如此,它不會正常工作。

爲簡單起見,您可以通過替代選擇.next('.PhotoLine')避免使用eq在所有(或只是.next(),但我喜歡精確,以避免意外的驚喜):

$('.PriceAndButton').each(function(i,el) { 
    $(this).insertAfter($(this).next('.PhotoLine')); 
}); 

http://jsfiddle.net/mblase75/YWaYN/

+0

已更新的回答。 – Blazemonger

+0

謝謝你對所有事情的清楚解釋! :) – user7954

1

你可以使用jQuery next method像這樣:

$(".PriceAndButton").each(function() { 
    var self = $(this); 
    self.insertAfter(self.next()); 
});