問題描述
我有一個 HTML 元素,其中包含大量無序列表。我需要將此元素克隆到頁面上的其他位置,添加不同的樣式 (這使用 jQuery 足夠簡單) 。
$("#MainConfig").clone(false).appendTo($("#smallConfig"));
然而,問題是所有的列表及其關聯的列表項都有 ID,clone
重複它們。有沒有辦法在追加之前用 jQuery 替換所有這些重複的 ID?
最佳解決方案
如果您需要一種在克隆這些列表項後引用列表項的方法,則必須使用類而不是 ID 。將所有 id = “…” 更改為 class = “…”
如果您正在處理遺留代碼或某些東西,並且無法將 ID 更改為類,則必須先刪除 id 屬性才能進行附加。
$("#MainConfig").clone(false).find("*").removeAttr("id").appendTo($("#smallConfig"));
請注意,您沒有辦法引用個別項目了。
次佳解決方案
由於 OP 要求一個方法來替換所有重複的 id 之前追加它們,也許這樣的事情可以工作。假設您想要在 HTML 塊中克隆 MainConfig_1,例如:
<div id="smallConfig">
<div id="MainConfig_1">
<ul>
<li id="red_1">red</li>
<li id="blue_1">blue</li>
</ul>
</div>
</div>
該代碼可能類似於以下內容,以查找克隆塊的所有子元素 (和後代),並使用計數器修改其 ID:
var cur_num = 1; // Counter used previously.
//...
var cloned = $("#MainConfig_" + cur_num).clone(true, true).get(0);
++cur_num;
cloned.id = "MainConfig_" + cur_num; // Change the div itself.
$(cloned).find("*").each(function(index, element) { // And all inner elements.
if(element.id)
{
var matches = element.id.match(/(.+)_d+/);
if(matches && matches.length >= 2) // Captures start at [1].
element.id = matches[1] + "_" + cur_num;
}
});
$(cloned).appendTo($("#smallConfig"));
要創建這樣的新 HTML:
<div id="smallConfig">
<div id="MainConfig_1">
<ul>
<li id="red_1">red</li>
<li id="blue_1">blue</li>
</ul>
</div>
<div id="MainConfig_2">
<ul>
<li id="red_2">red</li>
<li id="blue_2">blue</li>
</ul>
</div>
</div>
第三種解決方案
$("#MainConfig")
.clone(false)
.find("ul,li")
.removeAttr("id")
.appendTo($("#smallConfig"));
嘗試大小。 🙂
[編輯] 修正了 redsquare 的評論。
第四種方案
我使用這樣的東西:$(“#details”).clone() 。 attr(‘id’,’details_clone’).after(“h1”).show();
第五種方案
這是基於羅素的答案,但更多的審美和功能的形式。 jQuery 的:
$(document).ready(function(){
var cur_num = 1; // Counter
$('#btnClone').click(function(){
var whatToClone = $("#MainConfig");
var whereToPutIt = $("#smallConfig");
var cloned = whatToClone.clone(true, true).get(0);
++cur_num;
cloned.id = whatToClone.attr('id') + "_" + cur_num; // Change the div itself.
$(cloned).find("*").each(function(index, element) { // And all inner elements.
if(element.id)
{
var matches = element.id.match(/(.+)_d+/);
if(matches && matches.length >= 2) // Captures start at [1].
element.id = matches[1] + "_" + cur_num;
}
if(element.name)
{
var matches = element.name.match(/(.+)_d+/);
if(matches && matches.length >= 2) // Captures start at [1].
element.name = matches[1] + "_" + cur_num;
}
});
$(cloned).appendTo( whereToPutIt );
});
});
標記:
<div id="smallConfig">
<div id="MainConfig">
<ul>
<li id="red_1">red</li>
<li id="blue_1">blue</li>
</ul>
<input id="purple" type="text" value="I'm a text box" name="textboxIsaid_1" />
</div>
</div>
參考文獻
注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。