JQueryClone()破坏了我的html.能够多次复制同一代码的替代方案

JQuery Clone() mangles my html. Alternatives to be able to copy the same code several times?

本文关键字:复制 代码 方案 坏了 我的 html JQueryClone      更新时间:2023-09-26

我有一个使用JQuery UI的选项卡小部件的页面。其中2个选项卡共享同一段HTML,这只不过是一个简单的HTML表:

<table border="0" cellpadding="0" cellspacing="0" class="showTable" id="table-person-info">
    <tr>
        <td class="pictureColumn">
            <img alt="Person Photo" src="images/avatar.jpg" id="CurrPersonPhoto" />
        </td>                   
        <td>
            <div id="CurrPersonFullName" class="fullName"></div>
            <b class="popupInfo">Person ID:&nbsp;</b><div id="CurrPersonID" class="popupInfo"></div><br />
            <b class="popupInfo">Hire Date:&nbsp;</b><div id="CurrHireDate" class="popupInfo"></div><br />
            <b class="popupInfo">Tenure:&nbsp;</b><div id="CurrTenure" class="popupInfo"></div><br />
            <b class="popupInfo">Location:&nbsp;</b><div id="CurrLocation" class="popupInfo"></div>
        </td>
        <td style="width:179px;">
            <img src="edit.png" alt="Edit" />
            <img src="log_activity.png" alt="Log activity" />
        </td>
    </tr>
</table>

该表在ajax调用后得到更新,为了避免重复相同的代码两次,我尝试使用JQueryclone()函数将其注入到选项卡上需要显示的两个位置

$("#table-person-info").clone(false).find("*").removeAttr("id").appendTo($("#person-Info-View"));

将clone方法的参数从true更改为false似乎没有任何区别。我发现这段代码把html代码完全破坏成这样:

    <table border="0" cellpadding="0" cellspacing="0" class="showTable">    </table>
    <tr>
        <td class="pictureColumn">
        </td>                   
        <td>
        </td>
        <td style="width:179px;">
            <img src="edit.png" alt="Edit" />
            <img src="log_activity.png" alt="Log activity" />
        </td>
    </tr>
<img alt="Person Photo" src="images/avatar.jpg" />
<div id="CurrPersonFullName" class="fullName"></div>
<b class="popupInfo">Person ID:&nbsp;</b><div class="popupInfo"></div><br />
<b class="popupInfo">Hire Date:&nbsp;</b><div class="popupInfo"></div><br />
<b class="popupInfo">Tenure:&nbsp;</b><div class="popupInfo"></div><br />
<b class="popupInfo">Location:&nbsp;</b><div class="popupInfo"></div>

对JQuery文档的快速审查表明,这实际上是意料之中的事,我引用:

使用.clone()克隆未附加到DOM的元素集合时,它们插入DOM时的顺序不能保证

既然如此,我还有什么选择呢?我是否要重复该表,并在每次选择选项卡时手动更新值?我的意思是,只有两次,我想这并不难,但我想知道是否有更优雅的替代方案,或者我是否没有采取正确的方法来使用JQuery重用html代码。

很抱歉发了这么长的帖子,谢谢你的建议!

执行此代码时:

$("#table-person-info").clone(false)
    .find("*").removeAttr("id")
    .appendTo($("#person-Info-View"));

您已经使用find进入了一个新的选择,因此您将附加所有具有已删除ID的元素,而不是原始父表。试试这个:

$("#table-person-info").clone(false)
    .find("*").removeAttr("id").end()
    .appendTo($("#person-Info-View"));

我知道这可能需要更长的时间来编写,不知道你是否在使用自己的对象,但你有没有想过在你的场景中使用jQuery模板?您可以很容易地将模板绑定到一个对象,只需在后端更新对象,这将自动更新您的表,并且与每次更新整个表相比,所需的处理要少得多。