首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >for of循环和事件

for of循环和事件
EN

Stack Overflow用户
提问于 2019-06-19 08:38:17
回答 1查看 23关注 0票数 0

当我使用for of并将按钮设置为div.pane的第一个元素子级时

不是关闭每个div,而是关闭最后一个div。

代码语言:javascript
复制
for(pane of panes){
   pane.firstElementChild.onclick = () => pane.remove();
}

完整代码请访问codepen:https://codepen.io/Howaida/pen/JQRLME

当我使用相同的代码,但唯一的不同是我使用insertAdjacentHtml将按钮插入到js的第一个子级时,代码会按照我的预期工作,并且当我按下按钮时,它会关闭每一次跳水。

代码语言:javascript
复制
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

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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-06-19 08:55:13

如果没有panelet声明,该变量将成为全局变量,您将设置一个闭包。当循环结束时,它会引用最后一个被迭代的对象。使用let可以提供块级作用域,并允许每次循环迭代保持其自己的作用域。

代码语言:javascript
复制
const panes = document.querySelectorAll('.pane');
for(let pane of panes){
   pane.firstElementChild.onclick = () => pane.remove();
}
代码语言:javascript
复制
*{
  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;
}
代码语言:javascript
复制
<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>

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56658673

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档