Javascript/JQuery遍历表行和单元格,并向控制台输出一组选中的复选框

Javascript/JQuery iterate through table rows and cells and output an attr of checked checkboxes to console

本文关键字:输出 一组 复选框 控制台 遍历 JQuery 单元格 Javascript      更新时间:2023-09-26

我有以下代码,它应该遍历每个表行并转储我的数组,该数组是在javascript的前面一段声明的。然后,如果复选框被选中,并且它有一个attr"changed=yes",那么它应该被推到数组中,值应该输出到控制台,以及"path"属性,它应该作为一个变量输出,每次函数发现一个新的复选框被选中和更改时,该变量可以被覆盖。那么我的代码有什么问题呢?这些函数包含在一个函数中,当用户单击表单上的submit时调用该函数。

JsFiddle: http://jsfiddle.net/hU89p/392/

        $('#myTable1 tr').each(function(){
        myArray = [];
                    $.each($("input[type='checkbox']:checked").closest("td").siblings("td"),
                    function () {
                    if($(this).data("changed") == 'yes'){
                        myArray.push($(this).attr('checkboxtype'));
                        filepath = $(this).attr('path');
                        console.log(myArray);
                        console.log(filepath);
                    }
                });
            });

这是工作小提琴:

保持简洁:

$('#myTable1 tr').each(function() {
       var columns = $(this).find('td');
       columns.each(function() {
           var box = $(this).find('input:checkbox');
           if(box.is(":checked") && box.attr("changed") == 'yes')
           {
                myArray.push(box.attr('checkboxtype'));
                filepath = box.attr('path');                            
            }
        });
    });
         console.log(myArray);
  });

您应该使用$("input[type='checkbox']:checked").closest("td").siblings("td").each()

$().each()$.each()的区别

try this :-
     $('#myTable1 tr').each(function () {
                myArray = [];
                $(this).find("td input:checkbox").each(function () {
                    if ($(this).is(":checked") && $(this).attr("changed") == 'yes') {
                        myArray.push($(this).attr('checkboxtype'));
                        filepath = $(this).attr('path');
                        console.log(myArray);
                        console.log(filepath);
                    }
                });
            });