jQuery: How to count table columns?

前端 未结 15 1476
天命终不由人
天命终不由人 2020-12-28 13:20

Using jQuery, how would you figure out how many columns are in a table?



15条回答
  •  眼角桃花
    2020-12-28 13:27

    With jQuery and reduce it could look like this:

    $.fn.tableCellCount = function() {
        return $(this).find('tr:first td, tr:first th').get().reduce(function(a,b) {
            return a + ($(b).attr('colspan') ? parseInt($(b).attr('colspan')) : 1);
        },0)
    }
    
    $('table').tableCellCount();
    

    Or even simpler:

    $.fn.tableCellCount = function() {
        return $(this).find('tr:first td, tr:first th').get().reduce(function(a,b) {
            return a + (b.colSpan ? parseInt(b.colSpan) : 1);
        },0)
    }
    
    $('table').tableCellCount();
    

提交回复
热议问题