jQuerytr(table行)对象不能使用twice/multiple次?

jQuery tr (table row) object can not be used twice/multiple times?

问题见代码注释:

使用jQuery从JSON对象动态创建的tr对象不能重复使用以追加到不同的表中?

function myfunc(obj)
{
    //obj is JSON object

    jQuery('#ClientInfo').html('');
    jQuery('#clientListTable2G').html('');

    jQuery.each(obj, function( key, objClient ) {

        var tr = jQuery('<tr>').append(     
            jQuery('<td>').text(objClient.hostname),
            jQuery('<td>').text(objClient.mac),
            jQuery('<td>').text(objClient.rssi),
            jQuery('<td>').text("Wifi 2.4G"),
            jQuery('<td>').text(objClient.ip)            
        ).appendTo('#ClientInfo');


        /* HERE IS THE QUESTION */
        //If i uncomment below line than the #ClientInfo becomes blank and the tr row fills in #clientListTable2G only

        //jQuery('#clientListTable2G').append(jQuery(tr));
    });
}

您需要使用clone(),因为当您创建对象并追加到任何元素时,变量仍指向插入的项目。因此,当您使用 append 时,它只会移动元素。使用克隆创建元素的副本,然后我们可以正常插入它们。

jQuery.each(obj, function( key, objClient ) {
    var tr = jQuery('<tr>').append(     
        jQuery('<td>').text(objClient.hostname),
        jQuery('<td>').text(objClient.mac),
        jQuery('<td>').text(objClient.rssi),
        jQuery('<td>').text("Wifi 2.4G"),
        jQuery('<td>').text(objClient.ip)            
    );
    tr.appendTo('#ClientInfo');
    tr.clone().appendTo('#clientListTable2G');
});

您正在创建一个 jQuery 对象,然后尝试在一个地方追加并在另一个地方使用相同的对象。当您将 jQuery 对象附加到任何其他元素时,它将从当前位置删除并添加到新元素中。

您必须创建一个 html 字符串,然后创建 jQuery 对象或直接附加字符串。见下面代码

function myfunc(obj)
{
    //obj is JSON object

    jQuery('#ClientInfo').html('');
    jQuery('#clientListTable2G').html('');

    jQuery.each(obj, function( key, objClient ) {

         var tr = '<tr><td>'+ objClient.hostname+'</td><td>'
                  + objClient.mac+'</td><td>'+ objClient.rssi 
                  + '</td><td>'+"Wifi 2.4G"+'</td><td>'
                 +objClient.ip +'</td></tr>';
         $('#ClientInfo').append(tr);


        /* HERE IS THE QUESTION */
        //If i uncomment below line than the #ClientInfo becomes blank and the tr row fills in #clientListTable2G only

        $('#clientListTable2G').append(tr);
    });
}