当我用于
并将按钮设置为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

不应给出相同的结果,并且
为什么在第一种情况下不起作用?

最佳答案

如果没有letpane声明,则该变量将变为全局变量,并设置了闭包。循环结束时,它引用了最后一个迭代的对象。使用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>

关于javascript - for循环和事件,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/56658673/

10-13 04:22