gpt4 book ai didi

javascript - 克隆作为唯一元素的元素

转载 作者:太空宇宙 更新时间:2023-11-04 06:31:58 24 4
gpt4 key购买 nike

我正在用隐藏的 div 创建克隆,我创建了一个函数来显示隐藏的 div,但该函数目前只影响原始元素。如何创建影响单个克隆的函数?

我想我必须在每个循环中更改每个 id,但我不知道我是否得到了这个更改,而且我仍然不知道,我将如何传递将受到影响的 div 的 id,因为函数的参数

father = document.getElementById('father')
child = document.getElementById('child')

function showDescription(id) {
const divHidden = document.getElementById("idElement")
divHidden.classList.toggle('hide');
}

for (let i = 0; i < 5; i++) {
var newElement = child.cloneNode(true);
newElement.id = "idElement" + i;
father.appendChild(newElement);
}
<div id="father">
<div id="child">
<div class="row" Onclick="showDescription()">
<div class="col-md-10">
<h3>Bolsonaro ainda no Hospital têm recaida e está com pneumonia</h3>
</div>
</div>
<!-- Div Occult -->
<div id="idElement" class="hide col-md-12">
<p>O presidente Jair Bolsonaro (PSL) teve episódio isolado zde febre nesta quarta-feira </p>
</div>
</div>
</div>

我希望通过点击一个克隆的 div,它显示只隐藏在相应元素中的 div

最佳答案

你可以做的是为每个 newElement 添加事件监听器因为它们被创建。我用了 <template>标记,因为它似乎更适合标记标记。

<div id="father"></div>
<template id="child-template">
<div class="child">
<div class="row">
<div class="col-md-10">
<h3>Bolsonaro ainda no Hospital têm recaida e está com pneumonia</h3>
</div>
</div>
<!-- Div Occult -->
<div class="hide col-md-12 description">
<p>O presidente Jair Bolsonaro (PSL) teve episódio isolado zde febre nesta quarta-feira </p>
</div>
</div>
</template>

<script>
const father = document.getElementById('father');
const childTemplate = document.getElementById('child-template');

for (let i = 0; i < 5; i++) {
// clone the template and get the first child in the template tag (.child)
const newElement = childTemplate.content.cloneNode(true).children[0];
// add event listener to div with `row` class to
// toggle the div with `description` class
newElement.querySelector('.row').addEventListener('click',
() => newElement.querySelector('.description').classList.toggle('hide')
);
father.appendChild(newElement);
}
</script>

关于javascript - 克隆作为唯一元素的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54599384/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com