onmouseenter事件监听器不适用于动态创建的html元素

时间:2018-08-23 14:11:49

标签: javascript event-listener

动态创建的元素上的onmouseenter事件不起作用。 显示showOverlay()未定义。  index.html
 。  。  

 <div class="container-fluid">
  <div class="navigation-control"><ul></ul></div>
  <div class="heading">
    <h2></h2>
  </div>
  <div class="filters d-flex justify-content-end"></div>
    <div class="container-wallpapers">
     <div class="col-wallpaper"></div>
     <div class="col-wallpaper"></div>
     <div class="col-wallpaper"></div>
     <div class="col-wallpaper"></div>
     <div class="loading-wallpapers">
       <h4>LOADING WALLPAPERS</h4>
     </div>
    </div>
    <div class="scroll-toolbar" hidden>
      <div class="logo-toolbar">
        <h6><span>W</span>all<span>Truder</span></h6>
      </div>
        <ul>
          <li class="scroll-toolbar-gototop">
            <i class="material-icons">arrow_upward</i>
            <h6>Top</h6>
          </li>
        </ul>
    </div>
</div>
 <script src="assets/js/binder.js" type="module"></script>
 </body>
 </html>

binder.js

这是在调用元素时创建元素的函数。

       function createContainerWallpaper(src, username, usernameLink, 
           source, 
       sourceUrl){
        let containerWallpaper = document.createElement("div");
       containerWallpaper.setAttribute("class", "container-wallpaper");
       containerWallpaper.innerHTML = `<div class="main-wallpaper" 
       onmouseenter="showOverlay(event)">
           <img src="${src}"/>
           <div class="wallpaper-overlap">
             <div>
               <a href="${sourceUrl}" target="_blank">${source}</a>
               <a href="${usernameLink}" target="_blank">${username}</a>
             </div>
           </div>
         </div>`;
       return containerWallpaper;
       }

onmouseenter事件侦听器

function showOverlay(event){
       console.log(event.target);
        }

我也通过在使用window.onload函数加载元素后设置事件侦听器来进行尝试,但是它没有用。请在这里帮助我

1 个答案:

答案 0 :(得分:0)

您还可以创建div,它将使用mouseenter来监听document.createElement事件,并为其分配事件监听器,然后再执行innerHTML

基本示例:

function showOverlay() {
  alert('Showing...');
}

const $demo = document.querySelector('#demo');
const $insertedDiv = document.createElement('div');

$insertedDiv.setAttribute('id', 'inserted');
$insertedDiv.addEventListener('mouseenter', showOverlay);


$insertedDiv.innerHTML = '<span class="white">Appended with innerHTML</span>'

$demo.appendChild($insertedDiv);
#demo {
  width: 500px;
  height: 300px;
  background: #CCC;
}

#inserted {
  width: 100px;
  height: 100px;
  background: #000;
  margin: auto;
}

.white {
  color: #FFF;
}
<div id="demo"></div>