【问题标题】:Error when using variable with jQuery Selector使用带有 jQ​​uery 选择器的变量时出错
【发布时间】:2018-11-02 22:38:27
【问题描述】:

我正在尝试获取 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);

我得到的结果:

溜溜球

未定义

预期结果:

溜溜球

df

【问题讨论】:

  • 我认为您需要在&gt; 之前有一个空格,即$('.' + abc + ' &gt; .dSigh').attr('id');。而且,.dSigh 不是.yoyodirect child。所以你可以试试$('.' + abc + ' .dSigh').attr('id');
  • @showdev,你是救命恩人!!!

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


【解决方案1】:

删除child combinator (&gt;),因为.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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多