Add table row in jQuery

前端 未结 30 2337
既然无缘
既然无缘 2020-11-21 05:40

What is the best method in jQuery to add an additional row to a table as the last row?

Is this acceptable?

$(\'#myTable\').append(\'

        
30条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-21 06:18

    In my opinion the fastest and clear way is

    //Try to get tbody first with jquery children. works faster!
    var tbody = $('#myTable').children('tbody');
    
    //Then if no tbody just select your table 
    var table = tbody.length ? tbody : $('#myTable');
    
    //Add row
    table.append('hello>');
    

    here is demo Fiddle

    Also I can recommend a small function to make more html changes

    //Compose template string
    String.prototype.compose = (function (){
    var re = /\{{(.+?)\}}/g;
    return function (o){
            return this.replace(re, function (_, k){
                return typeof o[k] != 'undefined' ? o[k] : '';
            });
        }
    }());
    

    If you use my string composer you can do this like

    var tbody = $('#myTable').children('tbody');
    var table = tbody.length ? tbody : $('#myTable');
    var row = ''+
        '{{id}}'+
        '{{name}}'+
        '{{phone}}'+
    '';
    
    
    //Add row
    table.append(row.compose({
        'id': 3,
        'name': 'Lee',
        'phone': '123 456 789'
    }));
    

    Here is demo Fiddle

提交回复
热议问题