简体   繁体   English

Mouseenter事件未能触发

[英]Mouseenter Event Failing to Trigger

I have a set of 3 menu items that i'm trying to add a mouseenter event to. 我有一组3个菜单项,我正在尝试向其中添加mouseenter事件。 I can't seem to get it to work at all. 我似乎根本无法使用它。 I've also tried looping through the .menu-item class and nothing is happening. 我也尝试遍历.menu-item类,但没有任何反应。

It's driving me nuts. 它让我发疯。 Does anyone know why this isn't working? 有人知道为什么这行不通吗?

Many thanks in advance for any help 非常感谢您的任何帮助

Code is below and Codepen link is: https://codepen.io/emilychews/pen/VzaOoe 代码在下面,Codepen链接为: https ://codepen.io/emilychews/pen/VzaOoe

(Also I can't have a jQuery solution). (而且我没有jQuery解决方案)。

JS JS

var menuItem = document.querySelectorAll('.menu-item');

  function myMouseEnter() {

    alert('mouse entered');

  }

menuItem.addEventListener('mouseenter', myMouseEnter, false)

Commented-Out Version Using a Loop 使用循环注释掉的版本

//   function myMouseEnter() {

//     for(i=0; i < menuItem.length; i++){

//        alert ('mouse entered');
//       
//       }

//     }

//   menuItem.addEventListener('mouseenter', myMouseEnter, false)

CSS CSS

.menu-item {
padding: 10px;
font-family: arial;
}

HTML HTML

<ul class="unclick--menuitems">
  <li class="menu-item item1"><a href="//google.com">About</a></li>
  <li class="menu-item item2"><a href="//google.com">Work</a></li>
  <li class="menu-item item3"><a href="//google.com">Contact</a></li>
</ul>

You have to iterate throw the collection and add event listener on each element like this : 您必须像这样反复迭代抛出集合并在每个元素上添加事件侦听器:

var menuItems = document.querySelectorAll('.menu-item');

function myMouseEnter() {
 alert('mouse entered');
}

for(var i=0; i < menuItems.length; i++) {
  menuItems[i].addEventListener('mouseenter', myMouseEnter, false);
}

JS query selectors will always return the element in the form of array, so in your case you can use something like this, JS查询选择器将始终以数组形式返回该元素,因此在您的情况下,您可以使用类似这样的内容,

var menuItems = document.querySelectorAll('.menu-item');

function myMouseEnter() {
 console.log('mouse entered');
}

menuItems[0].addEventListener('mouseenter', myMouseEnter);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM