.closest(),类名返回空对象

时间:2014-06-16 13:05:55

标签: jquery html

this SO question中获取提示,我采用了类似的方法,使用jQuery的.closest()方法来定位元素。

HTML

<tr class="open"><td colspan="3">When 1 is clicked, target this tr</td></tr>
<tr>
  <td colspan="3">
      <table>
         <tbody>
            <tr>
               <td class="first-level">1</td> <!-- Click 1 -->
               <td>Some label</td>
            </tr>
         </tbody>
      </table>
  </td>
</tr>
<tr class="open"><td colspan="3">When 2 is clicked, target this tr</td></tr>
<tr>
  <td colspan="3">
      <table>
         <tbody>
            <tr>
               <td class="first-level">2</td> <!-- Click 2 -->
               <td>Some label</td>
            </tr>
         </tbody>
      </table>
  </td>
</tr>
<tr class="open"><td colspan="3">When 3 is clicked, target this tr</td></tr>
<tr>
  <td colspan="3">
      <table>
         <tbody>
            <tr>
               <td class="first-level">3</td> <!-- Click 3 -->
               <td>Some label</td>
            </tr>
         </tbody>
      </table>
  </td>
</tr>

的jQuery

$('#example tbody').on('click', 'td.first-level', function () {
      var tr = $(this).closest('.open'); // this is returning empty
});

JSFiddle

编辑:我无法使用colspan属性来遍历DOM,因为有时它甚至可能不存在。

因此,出于演示目的,我们假设用户点击了包含2的td。因此,在这种情况下,选择适当的tr的方法是什么?

1 个答案:

答案 0 :(得分:3)

您需要使用:

 $(this).closest('td[colspan="3"]').parent().prev();

 $(this).closest('table').closest('tr').prev();

<强> Working Demo

使用顶级父表:

$(this).closest('#example').find('.open');

<强> Working Demo