使用jquery设置复选框时遇到麻烦

阿尼班·查特吉

我有一个表,其行是动态生成的。总体结构如下:

<table id="table1">
 <thead></thead>
 <tbody>
   <tr>
    <td>Cell value 1</td>
    <td>Cell value 2</td>
    <td>Cell value 3</td>
    <td>
     <input type="checkbox" id="checkbox1" value="value1>
     <input type="checkbox" id="checkbox2" value="value2>
    </td>
   </tr>
   <tr>
    <td>Cell value 4</td>
    <td>Cell value 5</td>
    <td>Cell value 6</td>
    <td>
     <input type="checkbox" id="checkbox1" value="value1>
     <input type="checkbox" id="checkbox2" value="value2>
    </td>
   </tr>
 </tbody>
</table>

根据其中之一(准确地说是第三个)中的值,我尝试选中/取消选中复选框。我的脚本同样是:

$('#table1 tbody tr').each(function(){
 var cellValue = $(this).find("td").text();
 if (cellValue=='someValue'){
  $('#checkbox1).prop('checked',true);
 }
});

我面临的问题是,由于行是动态生成的,因此在该迭代期间,我无法获得该组特定的复选框。像上面的示例一样,在第一次迭代期间,我设置了checkbox1,并且工作正常,但是在第二次迭代期间,我试图在第二行中设置checkbox2,但第一行中的checkbox2被设置了。任何帮助/指针将不胜感激。谢谢。

彼得·卡

您可以td通过使用来获得第三个.eq(2),然后针对checkbox您可以使用的正确目标

$('.checkbox1', this)... //OR
$(this).find('.checkbox1').... 

根据条件语句的不同,可以使用数组.includes()方法将它们组合为一个,如下面的演示所示:

$('#table1 tbody tr').each(function() {
    var cellValue = $(this).find("td").eq(2).text();
    console.log(cellValue);
    if ( ['Cell value 3','Cell value 6'].includes(cellValue) ){
        $('.checkbox1', this).prop('checked',true);
    }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="table1">
 <thead></thead>
 <tbody>
   <tr>
    <td>Cell value 1</td>
    <td>Cell value 2</td>
    <td>Cell value 3</td>
    <td>
     <input type="checkbox" class="checkbox1" value="value1">
     <input type="checkbox" class="checkbox2" value="value2">
    </td>
   </tr>
   <tr>
    <td>Cell value 4</td>
    <td>Cell value 5</td>
    <td>Cell value 6</td>
    <td>
     <input type="checkbox" class="checkbox1" value="value1">
     <input type="checkbox" class="checkbox2" value="value2">
    </td>
   </tr>
 </tbody>
</table>

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章