我有两个 div,第二个是从第一个使用克隆而来的:
function dupe() {
var cc = document.getElementById("cc"); // original
var cc2 = cc.cloneNode(true); // clone
cc.parentNode.appendChild(cc2);
$('#cc :input').attr('disabled', true);
document.getElementById("cc").style.opacity = "0.5"; // affects original, which is fine
document.getElementById("radioNew").checked = true; // affects original, but needs to affect clone
}
然而,这一行不影响克隆,而是影响原始的,就像它上面的行:
document.getElementById("radioNew").checked = true;
由于克隆ID相同,如何选择克隆中的ID?我是否必须创建一个函数来重命名克隆中的所有 ID?
最佳答案
要使用 id 正确执行此操作,您需要更改所有嵌套节点中的所有 id 属性,因为您创建了一个“深”克隆。
当您确实需要像这样克隆节点时,我建议不要通过 ID 来标识节点,而应通过其他一些选择器来标识节点,例如 CSS(伪)类。使用 jQuery 这很容易:
HTML:
<!-- Note: class attributes instead of id -->
<div class="cc">
<div class="radioNew">
...
</div>
</div>
JS:
var original = $('.cc');
var clone = original.clone();
original.find('.radioNew').attr( ... ); <--- finds subelement of original
clone.find('.radioNew').attr( ... ); <--- finds subelement of clone
关于javascript - 如何选择重复的 DIV ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45863853/