2010-08-06 77 views
1

我有一個簡短的問題。循環多個div和這些div中的input/textarea的最有效方法。jQuery Loop問題

例如,我有以下HTML

<div class="formatInput"> 
     <h4>Section Header</h4> 
     <input type="text" class="formatSectionHeader" width="100%"/> 
     <h4>Section Content</h4> 
     <textarea class="formatSectionContent"></textarea> 
     <p style="float:right;"><span class="removeFormatInput">Remove Section</span></p> 
    </div> 

我做了一個按鈕,將允許用戶如果需要添加更多.formatInput的div。

在它結束時我有一個刷新按鈕,我想通過每個div循環並按順序收集輸入和textarea控件的值。

回答

1

遍歷的div,然後形成元素:

$('.formatInput').each(function(index) { 
    $(':input', this).each(function(index2)) { 
    alert(index + '-' + index2 ': ' + $(this).value()); 
    }); 
}); 
1

如果你打電話給$(".formatInput")它會給你所有帶有formatInput類的divs。使用.each()進行遍歷。

$(".formatInput").each(function(){ 
    // $(this) here will be the current div in the loop. 
}); 
1

有一件事值得一至少提的是,你可能尋找serialize,雖然我不能肯定地說。我說這是因爲這個措辭。

通過每個格循環,就像我說不過,也許你真的只是尋找一對夫婦的each電話收集輸入和文本區域控件的值,以便

0

您可以使用each遍歷所有的字段中輸入您的div裏面是這樣的:

$('.formatInput :input').each(function() { 
    alert($(this).value()); 
}); 

:input過濾器選擇將選擇哪個是DIV內的所有投入(在你的情況下輸入類型的文本和文本域)與類formatInput然後each用於循環它們。

0

以下將創建兩個單獨的數組。真的取決於你將如何處理數據,以確定如何格式化數據。 jAndy在頭上擊中了它,但我還不能投票。

var header = new Array(); 
var content = new Array(); 

$(".formatInput").each(function(){ 
    iDex = $(this).index(); 
    header[iDex] = $(this).children(".formatSectionHeader").val(); 
    content[iDex] = $(this).children(".formatSectionContent").val(); 
});