繁体   English   中英

JQuery Clone()破坏了我的html。 可以多次复制相同代码的替代方案?

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

我有一个使用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调用之后表会更新,并且为了避免重复相同的代码两次,我尝试使用JQuery clone()函数将其注入到我需要显示它的选项卡上的2个点。 我用过这个电话:

$("#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模板? 您可以非常轻松地将模板绑定到对象,只需更新后端中的对象,这将自动更新您的表,并且每次更新时克隆整个表所需的处理要少得多。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM