JavaScript动态添加元素后hover事件失效问题求解
解决动态新增元素无法触发JavaScript hover事件的问题
问题原因
你的代码在页面初始化时,仅对当时已存在的.zone div元素绑定了mouseenter和mouseleave事件。但动态新增的元素是在初始化之后创建的,没有被绑定事件,因此无法触发hover效果。
解决方案一:事件委托(推荐)
利用事件冒泡机制,将事件绑定到父元素.zone上,通过判断事件触发的目标元素是否符合条件,来实现所有静态/动态元素的hover效果。这种方式只需绑定一次事件,性能更优,也无需每次新增元素重复绑定。
修改后的JavaScript代码:
function addElemnt(){ var div = document.createElement('div'); div.innerHTML = 'Hi there - Element!'; div.className = 'box m-2'; document.querySelector('.zone').appendChild(div); } // 绑定事件到父元素.zone const zone = document.querySelector('.zone'); zone.addEventListener('mouseenter', (e) => { // 验证目标元素是否是我们需要的.box元素 if(e.target.classList.contains('box')){ e.target.style.backgroundColor = 'red'; } }); zone.addEventListener('mouseleave', (e) => { if(e.target.classList.contains('box')){ e.target.style.backgroundColor = ''; } });
解决方案二:创建动态元素时直接绑定事件
在addElemnt函数中,创建新div后立即为其绑定hover事件,同时保留初始元素的事件绑定逻辑。这种方式适合元素数量较少的场景,但频繁新增元素时会重复绑定事件,性能不如事件委托。
修改后的JavaScript代码:
function addElemnt(){ var div = document.createElement('div'); div.innerHTML = 'Hi there - Element!'; div.className = 'box m-2'; // 给新创建的元素绑定hover事件 div.addEventListener('mouseenter', () => { div.style.backgroundColor = 'red'; }); div.addEventListener('mouseleave', () => { div.style.backgroundColor = ''; }); document.querySelector('.zone').appendChild(div); } // 给页面初始存在的元素绑定事件 let hover = document.querySelectorAll('.zone div'); for (let elem of hover) { elem.addEventListener('mouseenter', () => { elem.style.backgroundColor = 'red'; }); elem.addEventListener('mouseleave', () => { elem.style.backgroundColor = ''; }); };
完整示例代码(事件委托方案)
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Test</title> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65" crossorigin="anonymous"> <style> .box, .zone{ transition: .4s; } .zone{ padding: 16px; background: #bdbdbd21; min-width: 282px; min-height: 200px; } .box{ cursor: move !important; padding: 16px; box-shadow: 0 2px 2px -1px #a0a0cc; width: 250px; margin-bottom: 10px; border-radius: 4px; font-weight: 600; font-size: 18px; background-color: #FFF; } .status{ width: 30px; height: 8PX; background: gray; margin-bottom: 16px; border-radius: 8px; } .status.red{ background: red; } </style> </head> <body> <h1>Hello!</h1> <div class="container text-center"> <div class="row"> <div class="col p-3" style="background-color: silver;"> <a class="btn btn-primary" onclick="addElemnt()" role="button">+ Add Element</a> </div> <div class="col-8 zone"> <div class="box m-2">Hi there - 01!</div> <div class="box m-2">Hi there - 02!</div> </div> </div> </div> <script> function addElemnt(){ var div = document.createElement('div'); div.innerHTML = 'Hi there - Element!'; div.className = 'box m-2'; document.querySelector('.zone').appendChild(div); } const zone = document.querySelector('.zone'); zone.addEventListener('mouseenter', (e) => { if(e.target.classList.contains('box')){ e.target.style.backgroundColor = 'red'; } }); zone.addEventListener('mouseleave', (e) => { if(e.target.classList.contains('box')){ e.target.style.backgroundColor = ''; } }); </script> </body> </html>
内容的提问来源于stack exchange,提问作者Kleuton Novais
相关产品推荐
相关产品推荐

