2010-08-06 79 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(); 
});