【问题标题】:Elements lose javascript functionality after cloning克隆后元素失去 javascript 功能
【发布时间】:2021-08-16 07:11:53
【问题描述】:

以下是代码。我所做的是制作一个项目(第一个),当我将鼠标悬停在它的按钮上时,它的背景颜色变为红色等等。

我接下来所做的是克隆元素并将其附加到新的 div 中。 html(具有相同类的元素)是相同的,但鼠标悬停事件不再起作用。

我的问题是为什么它不起作用,我该如何解决?我也尝试通过将内部 HTML 复制到新元素来做同样的事情,但每次都是一样的。

const colorDiv = document.querySelector(".color-div");
const button = document.querySelector("button");
const mainContainer = document.querySelector(".main-container");

button.addEventListener("mouseover", function() {
  colorDiv.style.backgroundColor = "red";
});

button.addEventListener("mouseout", function() {
  colorDiv.style.backgroundColor = "seagreen";
});

const newItem = mainContainer.cloneNode(true);
document.querySelector(".new-container").appendChild(newItem);
.color-div {
  height: 300px;
  width: 300px;
  background-color: seagreen;
  margin: 10px;
  padding: 10px;
  transition: all .3s;
}
<!-- I will copy the div with main container class -->
<div class="main-container">
  <div class="color-div">Hello</div>
  <button>Change</button>
</div>

<!-- and append copied item to the following item -->
<div class="new-container"></div>

【问题讨论】:

  • 是的,这是预期的行为,没有克隆事件。您必须将事件附加到克隆元素或利用事件委托。见developer.mozilla.org/en-US/docs/Web/API/Node/cloneNodestackoverflow.com/questions/1687296/…
  • s您还必须在新项目上创建所有侦听器。见stackoverflow answer
  • 还有一个问题:改变背景颜色只是一个例子吗?或者到底为什么有人会通过 JS 而不是 CSS 来改变悬停时的颜色?
  • 那么我如何才能在我正在开发的其他人的网站上实现该功能。我不知道按钮中添加了哪些事件侦听器?
  • @ArunBohra,检查代码,看看按钮添加了什么事件监听器?

标签: javascript html css


【解决方案1】:

没有克隆事件,这里有一个快速修复:

const colorDiv = document.querySelector(".color-div");
const button = document.querySelector("button");
const mainContainer = document.querySelector(".main-container");

// If someone clicks on anywhere on the website THAT IS A BUTTON, then change the color.
document.addEventListener("mouseover", function(e) {
  if (e.target.matches("button")) {
    colorDiv.style.backgroundColor = "red";
  }
});

document.addEventListener("mouseout", function(e) {
  if (e.target.matches("button")) {
    colorDiv.style.backgroundColor = "seagreen";
  }
}); 

const newItem = mainContainer.cloneNode(true);
document.querySelector(".new-container").appendChild(newItem);

这应该适用于每个克隆。

【讨论】:

    猜你喜欢
    • 2011-11-03
    • 1970-01-01
    • 1970-01-01
    • 2016-12-29
    • 1970-01-01
    • 2021-03-28
    • 2012-04-11
    • 1970-01-01
    • 2016-11-25
    相关资源
    最近更新 更多