2016-03-15 46 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); 
    }); 
}