【问题标题】:foreach through div通过 div 进行 foreach
【发布时间】:2013-03-09 01:19:28
【问题描述】:

我在通过以下构造循环时遇到了一些麻烦:

<div id="items">
    <p id="test1">
        <select  name="1" id="1"><option>A</option><option selected>B</option></select>
        <input type="text" name="to" id="to">
        <input type="text" name="away" id="awy">
    </p>
    <p id="test2">
        <select  name="2" id="2"><option>A</option><option selected>B</option></select>
        <input type="text" name="to" id="to">
        <input type="text" name="away" id="awy">
    </p>
    <p id="test3">
        <select  name="3" id="3"><option>A</option><option selected>B</option></select>
        <input type="text" name="to" id="to">
        <input type="text" name="away" id="awy">
    </p>
</div>

我需要运行 test1、test2 和 test3 并读取所选选项和文本字段的值(选择、到、离开)。如果我在例如 test1 中只有一件事,那么执行此操作对查询没有问题:

$('#items').children('p').each(function () {...}

但如果我添加两个文本字段并想为每个测试 (1-3) 执行此操作,我不知道...

有什么想法吗? 谢谢!

【问题讨论】:

  • ID 必须是唯一的。
  • 向我们展示函数内部的代码!
  • ids 必须是唯一的......并且我认为是有效的 NCName:w3.org/TR/1999/REC-xml-names-19990114/#NT-NCName(必须以字母或下划线开头)
  • 使用class 来识别一组相似的元素。不要过度使用id

标签: javascript jquery


【解决方案1】:

Id 应该代表 DOM 中的唯一项。改用类,如下所示:

<input type="text" name="to" class="to">
<input type="text" name="away" class="awy">

【讨论】:

    【解决方案2】:

    这个怎么样?

    $('#items').find('select option:selected, input:text').each(function(){
          alert($(this).val()); //Value of each selected option and text field within the div
    });
    

    【讨论】:

      【解决方案3】:

      注意:首先为所有元素提供唯一的 id。

      以下代码可能对您有所帮助。

      $(‘p’).each(function(index){
      this.children().get(0).val();
      
      //now do for second and third also
      }
      

      【讨论】:

      • ‘’ 不是有效的字符串分隔符
      【解决方案4】:

      您甚至不需要执行.children 部分。

      试试这个:

      $('#items > p').each(function () {
          // you can then use $(this) to reference the currently iterated p element.
          // such as $(this).find('input[type="text"]:first');
          // or
          // $(this).find('input[type="text"]:last');
      });
      

      【讨论】:

      • 为什么不呢?顺便说一句,你的选择器是不同的。
      猜你喜欢
      • 2013-01-16
      • 2010-12-24
      • 2023-03-14
      • 1970-01-01
      • 2010-12-05
      • 1970-01-01
      • 1970-01-01
      • 2018-10-09
      • 1970-01-01
      相关资源
      最近更新 更多