【问题标题】:jQuery tr (table row) object can not be used twice/multiple times?jQuery tr(表格行)对象不能使用两次/多次?
【发布时间】:2016-06-30 17:33:53
【问题描述】:

查看问题代码中的注释:

用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));
    });
}

【问题讨论】:

  • 结束的tr在哪里???
  • 我不确定此语法中是否需要结束标记。但如果仅附加在一个表中,则可以使用。

标签: jquery object dynamic html-table row


【解决方案1】:

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

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');
});

【讨论】:

  • 这可行,但请您详细解释原因吗?
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 2021-05-01
    • 2019-02-18
    • 1970-01-01
    • 1970-01-01
    • 2013-07-10
    • 2020-11-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多