代码之家  ›  专栏  ›  技术社区  ›  st4ck0v3rfl0w

jquery循环问题

  •  1
  • st4ck0v3rfl0w  · 技术社区  · 14 年前

    我有个很快的问题。最有效的方法是循环通过多个div和这些div中的输入/文本区域。

    例如,我有以下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>
    

    我做了一个按钮,允许用户添加更多。如果需要,格式化输入分隔符。

    在它的末尾,我有一个刷新按钮,我想循环遍历每个DIV,并按顺序收集输入控件和文本区域控件的值。

    5 回复  |  直到 14 年前
        1
  •  1
  •   zwippie    14 年前

    循环遍历div,然后形成元素:

    $('.formatInput').each(function(index) {
      $(':input', this).each(function(index2)) {
        alert(index + '-' + index2 ': ' + $(this).value());
      });
    });
    
        2
  •  1
  •   Reigel Gallarde    14 年前

    如果你打电话 $(".formatInput") 它会给你所有的 div 具有类格式输入的。使用 .each() .

    $(".formatInput").each(function(){
       // $(this) here will be the current div in the loop.
    });
    
        3
  •  1
  •   Andy Gaskell    14 年前

    至少值得一提的是你 可以 正在寻找 serialize 尽管我不能肯定。我之所以这么说是因为这个措词。

    循环遍历每个DIV并按顺序收集输入控件和文本区域控件的值

    就像我说的,也许你只是在找 each 电话。

        4
  •  0
  •   Sarfraz    14 年前

    你可以使用 each 要像这样循环遍历DIV中的所有字段:

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

    这个 :input 筛选选择将选择所有输入(在您的情况下,输入类型为文本和文本区域),这些输入位于带类的DIV内。 formatInput 然后 每个 用于循环它们。

        5
  •  0
  •   Nick Hagianis    14 年前

    下面将创建两个单独的数组。这取决于您将如何处理数据,以及您希望如何格式化数据。詹迪直接击中了头部,但我还不能投票。

    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();
    });