现有(纯)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/