gpt4 book ai didi

javascript - 对所有选定的复选框使用函数

转载 作者:行者123 更新时间:2023-12-02 16:11:03 26 4
gpt4 key购买 nike

我在对所有选定的复选框使用 JavaScript 函数时遇到了一些问题。它的外观如下:

<script type="text/javascript">
function toggle(source) {
checkboxes = document.getElementsByName('checkbox');
for(var i=0, n=checkboxes.length;i<n;i++) {
checkboxes[i].checked = source.checked;
}
}
function backToActive(id){ // for a single item
$.ajax({
type: "POST",
url: '/backtoactive/'+id,
success: function(){
$("#line_"+id).hide(1000);
}
});
}
function massiveBackToActive(){ // for multiple checked items
var pids = checkedProducts.join();
$.ajax({
type: "POST",
data: { ids : pids },
url: '/massivebacktoactive/',
success: function(){
window.location.href = window.location.href;
}
});
}
function checkProduct(id){
var a = checkedProducts.indexOf(id);
if( a >= 0 ){
checkedProducts.splice(a,1);
}
else{
checkedProducts.push(id);
}
}
</script>

然后我有这个:

<tr>
<th>
<input type="checkbox" onClick="toggle(this)" />
</th>
<th>img</th>
<th>Name</th>
</tr>
<tr id="line_<?php echo $item->productid;?>">
<td>
<input type="checkbox" name="checkbox" onchange="checkProduct(<?php echo $item->productid;?>)" />
</td>
<td><a href="/item/?id=<?php echo $item->productid;?>" class="bold"><img src="<?php echo $item->imgurl;?>" /></a></td>
<td><a target="_new" href="<?php echo $item->url;?>" class="bold"><?php echo $item->name;?></a></td>
</tr>

现在,我遇到的问题是,如果我一一选择多个项目,一切都会很好。但是,如果我使用 selectall 复选框将它们全部选中,则该功能将不再起作用。我的意思是,它不适用于所选项目。

奇怪的是,如果我选择全部然后取消选择其中一些,该功能将应用于未选中的项目。它的行为就好像它跟踪点击一样,但我使用的是 onChange。有什么想法吗?

最佳答案

主要问题是以编程方式更改检查的属性值不会触发更改事件,因此当您使用全部检查时,checkedProducts数组将不会更新。

但是由于您正在使用 jQuery,请尝试完整的 jQuery 解决方案,因此请更改您的标记

<input type="checkbox" id="checkboxall" />

<input type="checkbox" name="checkbox" data-id="<?php echo $item->productid;?>" />

然后

$('#checkboxall').change(function () {
$('input[name="checkbox"]')[this.checked ? 'not' : 'filter'](':checked').prop('checked', this.checked).change();
})

$('input[name="checkbox"]').change(function () {
var id = $(this).data('id')
if (this.checked) {
checkedProducts.push(id);
} else {
var index = checkedProducts.indexOf(id);
if (index > -1) {
checkedProducts.splice(index, 1);
}
}

console.log(checkedProducts)
})

function backToActive(id) { // for a single item
$.ajax({
type: "POST",
url: '/backtoactive/' + id,
success: function () {
$("#line_" + id).hide(1000);
}
});
}

function massiveBackToActive() { // for multiple checked items
var pids = checkedProducts.join();
$.ajax({
type: "POST",
data: {
ids: pids
},
url: '/massivebacktoactive/',
success: function () {
window.location.href = window.location.href;
}
});
}

关于javascript - 对所有选定的复选框使用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30206681/

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