Web前端笔记-批量反选CheckBox

x33g5p2x  于2022-07-26 转载在 其他  
字(1.6k)|赞(0)|评价(0)|浏览(238)

说下这里需要实现的效果:

点击反选后:

这里推荐使用原生态的JS来搞,用Jquery(3.6版本)会有问题。

首先需要把每个CheckBox都设置好名字:

<table class="table text-center table-striped">
<thead class="thead-dark">
	<tr>
		<th><a class="text-white" href="#" onclick="invertSelection()">反选</a></th>
		<th>创建时间</th>
		<th>ID</th>
		<th>标题</th>
		<th>标签</th>
		<th>作者</th>
		<th>修改时间</th>
		<th>操作</th>
	</tr>
</thead>
<tbody>
	@foreach($article as $item)
		<tr>
			<td><input name="checkSelect" type="checkbox" id="checkSelect{{$item->id}}"></td>
			<td>{{$item->created_at}}</td>
			<td>{{$item->id}}</td>
			<td>{{$item->title}}</td>
			<td>标签</td>
			<td>站长</td>
			<td>{{$item->updated_at}}</td>
			<td>
				<a class="btn-sm btn-success text-white" href="{{route('noticeShow', ['id' => $item->id])}}">查看</a>
				<a class="btn-sm btn-primary text-white" href="{{route('noticeEdit', ['id' => $item->id])}}">编辑</a>
				<a class="btn-sm btn-danger text-white" href="{{route('noticeDelete', ['id' => $item->id])}}">删除</a>
			</td>
		</tr>
	@endforeach
</tbody>

使用原生态的JS去干:

function invertSelection(){

    let checkSelect = document.getElementsByName("checkSelect");
    for(let i= 0;i < checkSelect.length; i++){

        checkSelect[i].checked = !checkSelect[i].checked;
    }
}

不要用JQuery的attr,pop,removeAttr,removePop这种,这种的有bug。

相关文章

微信公众号

最新文章

更多