如何正确使用children()来查找输入字段的名称和ID?

时间:2012-03-07 04:51:43

标签: jquery

这是一个例子

$newattribute.children("div").children("input,select").each(function (i) {
    var $currentElem = $(this);
    $currentElem.attr("name", $currentElem.attr("name") + current);
    $currentElem.attr("id", $currentElem.attr("id") + current);
});

HTML

<div>
  <table class="table">
    <tr>
      <td><select id="attribute_name" name="attribute_name">
          <option value="1">Size</option>
          <option value="2">Color</option>
        </select></td>
      <td><input type="text" id="attribute_value" name="attribute_value"></td>
      <td><input type="text" id="attribute_qty" name="attribute_qty"></td>
      <td><input type="text" id="attribute_price" name="attribute_price"></td>
    </tr>
  </table>
</div>

如何正确使用.children("div")查找name&amp; id

1 个答案:

答案 0 :(得分:2)

不要使用.children(),因为它会发现孩子们。如同,不是孙子,不是曾孙,只是直接的孩子。要查找后代,请使用.find()。所以:

$newattribute.children("div").find("input,select")

你没有说$newattribute是什么,但假设它是问题中显示的div元素的直接父元素,那么我刚刚显示的语句将找到所有输入并选择该div的后代元素

API doco for .children()进一步解释了这一点,并链接到doco for .find()