2016-03-15 42 views
0

查看该问题的代码中的评论:jQuery tr(表行)对象不能被使用两次/多次?

从json对象动态创建的j对象的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)); 
    }); 
} 
+0

其中是关闭tr ??? –

+0

我不确定在此语法中是否必须要求结束标记。但如果只附加在一个表中,则工作。 –

回答

1

你需要,因为当你创建一个对象,并追加到任何元素,变量仍指向插入项目使用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'); 
}); 
+0

这个工程,但你能详细解释原因吗? –

0

您正在创建一个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); 
    }); 
}