当我使用for of并将按钮设置为div.pane的第一个元素子级时
不是关闭每个div,而是关闭最后一个div。
for(pane of panes){
pane.firstElementChild.onclick = () => pane.remove();
}
完整代码请访问codepen:https://codepen.io/Howaida/pen/JQRLME
当我使用相同的代码,但唯一的不同是我使用insertAdjacentHtml将按钮插入到js的第一个子级时,代码会按照我的预期工作,并且当我按下按钮时,它会关闭每一次跳水。
for (let pane of panes) {
pane.insertAdjacentHTML("afterbegin", '<button class="remove-button">[x]</button>');
// button becomes the first child of pane
pane.firstChild.onclick = () => pane.remove();
}
完整代码请访问codepen:https://codepen.io/Howaida/pen/MMjVJN
不应该给出相同的结果,为什么它在第一种情况下不起作用?
发布于 2019-06-19 08:55:13
如果没有pane
的let
声明,该变量将成为全局变量,您将设置一个闭包。当循环结束时,它会引用最后一个被迭代的对象。使用let
可以提供块级作用域,并允许每次循环迭代保持其自己的作用域。
const panes = document.querySelectorAll('.pane');
for(let pane of panes){
pane.firstElementChild.onclick = () => pane.remove();
}
*{
margin:0;
Padding:0;
box-sizing:border-box;
border:none;
outline:none;
}
.pane{
width: 400px;
height:150;
border-top: 2px solid #c4df9b;
background-color: #e1ead7;
padding: 20px;
position: relative;
}
.pane button{
position: absolute;
right: 0;
top:0;
display: inline-block;
padding: 10px;
color: #8b0000;
font-weight: bold;
background-color: transparent;
}
<div class="pane">
<button class='remove-button'>[x]</button>
<h3>Horse</h3>
<p>The horse is one of two extant subspecies of Equus ferus. It is an odd-toed ungulate mammal belonging to the taxonomic family Equidae. The horse has evolved over the past 45 to 55 million years from a small multi-toed creature, Eohippus, into thelarge, single-toed animal of today.</p>
</div>
<div class="pane">
<button class='remove-button'>[x]</button>
<h3>Donkey</h3>
<p>The donkey or ass (Equus africanus asinus) is a domesticated member of the horse family, Equidae. The wild ancestor of the donkey is the African wild ass, E. africanus. The donkey has been used as a working animal for at least 5000 years.</p>
</div>
<div class="pane">
<button class='remove-button'>[x]</button>
<h3>Cat</h3>
<p>The domestic cat (Latin: Felis catus) is a small, typically furry, carnivorous mammal. They are often called house cats when kept as indoor pets or simply cats when there is no need to distinguish them from other felids and felines. Cats are oftenvalued by humans for companionship and for their ability to hunt vermin.</p>
</div>
https://stackoverflow.com/questions/56658673
复制相似问题