gpt4 book ai didi

javascript - 第二次全选和取消全选不起作用

转载 作者:行者123 更新时间:2023-12-01 02:27:23 25 4
gpt4 key购买 nike

我想使用按钮选择和取消选择所有内容。

第一次选择和取消选择下面的代码有效,但第二次,我的按钮不起作用。

HTML:

<button type="button" id="selectAll" class="main"> Select </button>
<button type="button" id="unselectAll" class="main"> UnSelect </button>

jQuery:

$("#selectAll").on("click", function() {

$("#example tr").each(function() {
$(this).find("input").attr('checked', true);
});
});

$("#unselectAll").on("click", function() {

$("#example tr").each(function() {
$(this).find("input").removeAttr('checked');
});
});

JSFiddle

我该如何解决这个问题?

最佳答案

使用 prop() 而不是 attr(),您可以将它们组合在一起,如下所示:

$("#selectAll, #unselectAll").on("click", function() {
var selectAll = this.id === 'selectAll';
// no need for `each` ... jQuery will do that internally already
$("#example tbody :checkbox").prop('checked', selectAll);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<button type="button" id="selectAll" class="main"> Select </button>
<button type="button" id="unselectAll" class="main"> UnSelect </button>

<table id="example" class="myclass" />
<thead>
<tr>
<th>
</th>
<th>Name</th>
<th>Company</th>
<th>Employee Type</th>
<th>Address</th>
<th>Country</th>
</tr>
</thead>
<tbody>

<tr>
<td>
<input type="checkbox" />
</td>
<td>varun</td>
<td>TCS</td>
<td>IT</td>
<td>San Francisco</td>
<td>US</td>
</tr>

<tr>
<td>
<input type="checkbox" />
</td>
<td>Rahuk</td>
<td>TCS</td>
<td>IT</td>
<td>San Francisco</td>
<td>US</td>
</tr>

<tr>
<td>
<input type="checkbox" />
</td>
<td>johm Doe</td>
<td>TCS</td>
<td>IT</td>
<td>San Francisco</td>
<td>US</td>
</tr>

<tr>
<td>
<input type="checkbox" />
</td>
<td>Sam</td>
<td>TCS</td>
<td>IT</td>
<td>San Francisco</td>
<td>US</td>
</tr>

<tr>
<td>
<input type="checkbox" />
</td>
<td>Lara</td>
<td>TCS</td>
<td>IT</td>
<td>San Francisco</td>
<td>US</td>
</tr>

<tr>
<td>
<input type="checkbox" />
</td>
<td>Jay</td>
<td>TCS</td>
<td>IT</td>
<td>San Francisco</td>
<td>US</td>
</tr>

<tr>
<td>
<input type="checkbox" />
</td>
<td>Tom</td>
<td>TCS</td>
<td>IT</td>
<td>San Franciso</td>
<td>US</td>
</tr>

</tbody>
</table>

关于javascript - 第二次全选和取消全选不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47521869/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com