jQuery的.children()方法返回'undefined'?

时间:2016-03-16 21:28:01

标签: javascript jquery html

在我的jQuery代码中,我希望能够在<tr>元素中获取子元素。我创建了一个jQuery对象并命名变量$trElement。但是,由于某种原因,调用$trElement.children(".sequence-edit")会返回undefined,因此对该语句执行的任何进一步操作都会引发错误(因为您正在对未定义的对象调用方法)。我检查了父元素的HTML代码,它显然包含一个带有指定类名的子元素。那么为什么它不起作用?

以下是我用来调试问题的代码。

console.log($trElement.html());
console.log($trElement.children(".sequence-edit"));

第一行console.log($trElement.html());记录:

<td class="sequence-number">#1</td>
<td class="sequence-data">
     <form action="editSequence.do" method="POST">
          <textarea cols="50" rows="10" name="sequence" class="sequence-data-textarea"></textarea>
          <input type="hidden" name="index" value="0">
     </form>
</td>
<td class="button-first">

     <!-- Element targeting through ".sequence-class" -->
     <button type="button" class="btn btn-info sequence-edit center-block display-true">EDIT</button>
     <button class="btn btn-info center-block edit-submit display-false" style="display: none;">SUBMIT</button>
</td>
<td class="button-second">
     <button type="button" class="btn btn-danger delete-modal-appearance center-block display-true" data-toggle="modal" data-target="#modal-delete-confirmation">DELETE</button>
     <button class="btn btn-warning center-block edit-cancel display-false" style="display: none;">CANCEL</button>
</td>
<td>
     <input type="checkbox" class="checkbox-delete-selection center-block">
</td>

第二行console.log($trElement.children(".sequence-edit"));记录:undefined

1 个答案:

答案 0 :(得分:2)

.children()只会向您的选择器(trElement)DOM树中移动一步(这些是您的<TD>,而不是您的<button>)。

而是使用.find(".sequence-edit")

<德尔> https://api.jquery.com/children/
https://api.jquery.com/find/

var $trElement = $("tr");
console.log( $trElement.find(".sequence-edit").html() ); // "EDIT"
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tr>
    <td class="sequence-number">#1</td>
    <td class="sequence-data">
      <form action="editSequence.do" method="POST">
        <textarea cols="50" rows="10" name="sequence" class="sequence-data-textarea"></textarea>
        <input type="hidden" name="index" value="0">
      </form>
    </td>
    <td class="button-first">
      <!-- Element targeting through ".sequence-class" -->
      <button type="button" class="btn btn-info sequence-edit center-block display-true">EDIT</button>
      <button class="btn btn-info center-block edit-submit display-false" style="display: none;">SUBMIT</button>
    </td>
    <td class="button-second">
      <button type="button" class="btn btn-danger delete-modal-appearance center-block display-true" data-toggle="modal" data-target="#modal-delete-confirmation">DELETE</button>
      <button class="btn btn-warning center-block edit-cancel display-false" style="display: none;">CANCEL</button>
    </td>
    <td>
      <input type="checkbox" class="checkbox-delete-selection center-block">
    </td>
  </tr>
</table>