[英]How to get the ID of a child when mouseover parent
I guess that my question is quite simple but I'm a real beginner in javascript and I can't find what I am looking for : 我想我的问题很简单,但我是javascript的真正初学者,我找不到我要找的东西:
I am trying to get the ID of a li when mouse is over the nav or ul... My HTML structure would be : 当鼠标在nav或ul上时,我试图获取li的ID ...我的HTML结构将是:
<nav><ul id="menu">
<li id="FirstLink">Link1</li>
<li id="SecondLink">Link2</li>
<li id="ThirdLink">Link3</li>
</ul></nav>
So my goal is to listen for a mouseover (and mouseout) event on each li, but a script with 10 listener (for 5 li) is too much dirty... 所以我的目标是在每个li上监听mouseover(和mouseout)事件,但是一个带有10个监听器(5 li)的脚本太脏了......
That's why I thought of a script like : 这就是为什么我想到一个像这样的脚本:
var menu = document.getElementById("menu");
menu.addEventListener('mouseover', myFunction, false);
function myFunction () {
//something that get the ID of the <li> that is currently under the mouse and can put it inside a variable as "Link1"
}
But if there is a better solution, I will be happy to know it ! 但如果有更好的解决方案,我会很高兴知道它! (I would like to stay in pure js) (我想留在纯粹的js)
var menu = document.getElementById("menu");
menu.addEventListener('mouseover', myFunction, false);
function myFunction (event) {
var li = event.target;
if( li.nodeName !== 'li' ) return;
// do your stuff with li
}
To get the ID of the hovered element you need to use event.target . 要获取悬停元素的ID,您需要使用event.target 。
For that you need to pass event
as a parameter in your function. 为此,您需要将event
作为函数中的参数传递。
Then you can get the .id attribute of that element. 然后,您可以获取该元素的.id属性。
function myFunction(event) {
show_result.innerHTML = event.target.id;
}
put the event on child elements only 仅将事件放在子元素上
var menu = document.getElementById("menu");
for( var counter = 0; counter< menu.childNodes.length; counter++)
{
menu.childNodes[ counter ].addEventListener('mouseover', function(){
alert( "id is " + this.id );
}, false);
}
http://jsfiddle.net/neuroflux/ssSnN/ http://jsfiddle.net/neuroflux/ssSnN/
and 和
$('#menu').children("li").on('mouseover', function() {
var childID = $(this).attr("id");
//YOUR ID WILL BE childID!
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.