如果父元素也有鼠标悬停,如何为子元素设置鼠标悬停事件?
我的页面上有一个“帮助”区域,每当用户将鼠标悬停在表格上时,帮助信息都应该更新。问题出在表格中,我在每行的1个单元格中有一个复选框,当用户将鼠标悬停在该复选框上时,我希望复选框的mouseover事件覆盖表事件并显示复选框帮助。目前,表格鼠标悬停工作正常,但是当我将鼠标悬停在复选框上时没有任何反应。如果父元素也有鼠标悬停,如何为子元素设置鼠标悬停事件?
<table class="myTable">
<tr>
<th>Col1</th>
<th>Col2</th>
</tr>
<tr>
<td><input class="myCheckbox" type="checkbox" /></td>
<td>Cell 2</td>
</tr>
<tr>
<td><input class="myCheckbox" type="checkbox" /></td>
<td>Cell 3</td>
</tr>
</table>
<div class="myHelpMenu"></div>
$('.myCheckbox').mouseover(function() {
$('.myHelpMenu').html("this is my checkbox help");
});
$('.myTable').mouseover(function() {
$('.myHelpMenu').html("this is my tables help");
});
这是使用mouseover
是徘徊在当前target
元,比用纯JS来检索,检测一个很好的方式.tagName
您可以创建一个消息列表对象并检索所需的一个。
$('.myTable').mouseover(function(e) {
var tag = e.target.tagName;
var messages = {
"INPUT" : "this is my checkbox help",
"TABLE" : "this is my tables help"
};
$('.myHelpMenu').text(messages[tag]);
});
如果你想清楚你的信息的消息不喜欢:
$('.myTable').on('mouseover mouseleave',function(e) {
var tag = e.target.tagName;
var messages = {
"INPUT" : "this is my checkbox help",
"TABLE" : "this is my tables help"
};
$('.myHelpMenu').text(messages[tag]);
if(e.type=='mouseleave')
$('.myHelpMenu').empty();
});
由于mouseover
该表是整个区域,只需拨打mouseenter
代替。然后,您可以在离开表格后添加mouseout
以重新更新。
但面临的挑战是输入复选框是表内,所以我怎么会触发该表的鼠标移开? – silvster27 2013-03-06 23:57:04
很多方法,但Mercurybullet在这里有最好的解决方案。的确很不错。 – Benjiman 2013-03-07 00:01:52
听起来就像你希望鼠标悬停的复选框停止传播到表?
如果是这样,这应该做到这一点。
$('.myCheckbox').mouseover(function(e) {
$('.myHelpMenu').html("this is my checkbox help");
e.stopPropagation();
});
这很好用! – silvster27 2013-03-06 23:58:36
很高兴我能帮到你。不要忘记标记答案,如果它有助于解决你的问题。 :) – Mercurybullet 2013-03-07 00:07:20
+1编码风格 – Popnoodles 2013-03-07 00:03:14
+1为甜蜜的“现场演示”按钮。 – Mercurybullet 2013-03-07 00:08:10
@Mercurybullet :)谢谢哈哈哈,但如果只是按钮“甜蜜”,你可以删除+1 :)(P.S你可以自由使用和滥用:D) – 2013-03-07 00:09:36