使用Javascript/Jquery迭代表行和复选框,如果选中,则将复选框的属性添加到数组中
我有一个PHP页面,每个表行中有5个复选框,我有一些Javascript代码,可以迭代所有复选框,以确定它们的值是否与最初从数据库中获取的值不同,如果复选框值已更改,则会为其分配属性changed='true'。我现在要做的是检查表中的每一行,如果选中了复选框,并且其属性更改为true,那么我想将其属性“checkboxtype”放在数组中,它应该显示在控制台中。当我的函数移到一个新的表行时,我的数组也应该被转储。我有下面的代码,但它不能正常工作使用Javascript/Jquery迭代表行和复选框,如果选中,则将复选框的属性添加到数组中,javascript,php,checkbox,html-table,Javascript,Php,Checkbox,Html Table,我有一个PHP页面,每个表行中有5个复选框,我有一些Javascript代码,可以迭代所有复选框,以确定它们的值是否与最初从数据库中获取的值不同,如果复选框值已更改,则会为其分配属性changed='true'。我现在要做的是检查表中的每一行,如果选中了复选框,并且其属性更改为true,那么我想将其属性“checkboxtype”放在数组中,它应该显示在控制台中。当我的函数移到一个新的表行时,我的数组也应该被转储。我有下面的代码,但它不能正常工作 $('#myTable1 tr').ea
$('#myTable1 tr').each(function(){
myArray = []; //dump array
$(this).find('td').each(function(){
boxes.each(function() { //function iterates through each input type of checkbox, it is defined in some earlier code
if(this.checked && $(this).data("changed") == 'yes'){
myArray.push($(this).attr('checkboxtype'));
console.log(myArray);
}
});
});
});
看起来很复杂,一个更好的jQuery选择器将处理大部分问题
myArray = [];
$('#myTable1 input:checked[data-changed=yes]')
.each(function() {
myArray.push($(this).attr('checkboxtype'));
});
我个人建议:
// selects the checkbox inputs:
var myArray = $('#myTable1 tr td input[type="checkbox"]').filter(function(){
// retains only those whose checked state has been changed:
return this.checked == this.defaultChecked;
// moves to the first td ancestor of those changed checkboxes:
}).closest('td').map(function() {
// pushes the content of the checkboxtype attribute to the map:
return this.getAttribute('checkboxtype');
// creates/forms the array:
}).get();
虽然不是创建您自己的无效属性,但我进一步建议使用HTML5的(有效)自定义data-*
属性,以提供一个属性,例如data checkboxtype
和jQuery:
var myArray = $('#myTable1 tr td input[type="checkbox"]').filter(function(){
return this.checked == this.defaultChecked;
}).closest('td').map(function() {
return $(this).data('checkboxtype');
}).get();
参考资料: