将变量与jQuery选择器一起使用时出错

时间:2018-11-02 22:38:28

标签: javascript jquery html ecmascript-6 jquery-selectors

我正在尝试获取td的ID,以对它们执行某些功能。我有多个此类,但是我需要这个特殊的td

这是我的代码:

HTML:

<table border=1 class="yo">
<tbody>
    <tr>
        <td>a</td>
        <td class="sigh">b</td>
    </tr>
</tbody>
</table>
<table border=1 class="yoyo">
<tbody>
    <tr>
        <td>x</td>
        <td class="dSigh" id="df">y</td>
    </tr>
</tbody>
</table>

jQuery:

 var abc = $('.yo').next().attr('class');
 console.log(abc);
 var tableBodyCols2 = $('.' + abc + '> .dSigh').attr('id');
 console.log(tableBodyCols2);

我得到的结果:

yoyo

未定义

预期结果:

yoyo

df

1 个答案:

答案 0 :(得分:0)

删除child combinator>),因为.dSigh不是.yoyo的直接子代。您需要使用descendant combinator(空格):

var abc = $('.yo').next().attr('class');
console.log(abc);
var tableBodyCols2 = $('.' + abc + ' .dSigh').attr('id');
console.log(tableBodyCols2);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table border=1 class="yo">
  <tbody>
    <tr>
      <td>a</td>
      <td class="sigh">b</td>
    </tr>
  </tbody>
</table>
<table border=1 class="yoyo">
  <tbody>
    <tr>
      <td>x</td>
      <td class="dSigh" id="df">y</td>
    </tr>
  </tbody>
</table>