使用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正在设置中。如有任何帮助/建议,我们将不胜感激。谢谢

使用.eq(2)获得第三个td,然后使用瞄准正确的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>

您不能生成具有相同id的元素。当函数首次执行时,它将选择具有该id的第一个元素。使用class="相反

如果你想存储每个检查的值,请检查:HTML元素数组,name=";某物[]";或者name=";什么";?

最新更新