javascript - 新 html 元素的旧 javascript 函数

标签 javascript html function

现有(纯)javascript 函数无法与新的 html 元素(在该函数之后创建)一起使用:

document.querySelector('li').onmouseover = function() {
  document.querySelector("li").innerHTML ="Hai soffermato il mouse qui!";
}

document.querySelector('li').onmouseout = function() {
  document.querySelector("li").innerHTML ="Sofferma il mouse qui";
}

document.getElementById('bottone1').onclick = function() {
  var Lista = document.getElementById('lista');
  var NuovoElemento = document.createElement('li');
  NuovoElemento.innerText = 'Nuova voce'; // innerHTML
  Lista.insertBefore(NuovoElemento, Lista.lastChild);
}
<p><b>Elenco puntato:</b></p>
<ol id="lista">
  <li>Sofferma il mouse qui</li>
</ol>
<button id="bottone1">Aggiungi voce</button>

是这样的(但不好,恕我直言),我知道。 但是,抱歉,我不明白这个线程,它解决了问题(widthout 解释了它):-( Javascript function doesn't work when creating a new HTML element

谢谢(更多独奏)。

最佳答案

您可以通过应用事件委托(delegate)的概念来解决这个问题。这意味着您将监听父元素上的鼠标事件,而不是 li 上的鼠标事件。元素。为了实现这一点,您需要查阅传递给回调函数的事件对象,并检查鼠标事件起源的原始元素确实是 li元素:

document.getElementById('lista').onmouseover = function(e) {
  if (e.target.tagName !== 'LI') return false;
  e.target.textContent ="Hai soffermato il mouse qui!";
}

document.getElementById('lista').onmouseout = function(e) {
  if (e.target.tagName !== 'LI') return false;
  e.target.textContent ="Sofferma il mouse qui";
}

document.getElementById('bottone1').onclick = function() {
  var Lista = document.getElementById('lista');
  var NuovoElemento = document.createElement('li');
  NuovoElemento.textContent = 'Nuova voce';
  Lista.insertBefore(NuovoElemento, Lista.lastChild);
}
<p><b>Elenco puntato:</b></p>
<ol id="lista">
  <li>Sofferma il mouse qui</li>
</ol>
<button id="bottone1">Aggiungi voce</button>

注意,我还介绍了 textContent 的使用以上受青睐的特性innerHTML分配纯文本时,以避免某些字符串可能产生的副作用(其中包含 <&)。

关于javascript - 新 html 元素的旧 javascript 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40320453/

相关文章:

javascript - Bootstrap-Select打开div下的选项

javascript - 使 HTML 表单元素出现(jQuery 或 JS)

javascript - 在 div 中重新执行硬编码的外部 JavaScript

asp.net - 在单独的选项卡/窗口中打开 PDF

function - 我可以在 Lua shell 提示符下运行函数吗?

r - 使用 mlr-package 构建模型时的自定义性能测量

javascript - 通过循环从 JSON 选择适当的单选按钮

javascript - 为什么我的 Javascript for 循环是连接数字而不是相加?

javascript - 浏览器性能显示/可见性

c - 在 C 中,我的程序输出不在用户输入数组内的数字或不是数组中任何数字的总和,不会打印任何内容