2014-01-07 146 views
0

我有一个动态的HTML内容如何使.hover()与.on()一起使用?

<div id="parent"> 
    <div class="child"> 
     Hover Text 
    </div> 
</div> 

当我尝试悬停“悬停文本”里子元素,此代码就不起作用。

$("#parent").on('hover', '.child', function() 
{ 
    alert("Hello"); 
}); 

这个代码既不

$('#parent').on('hover', '.child', function(e) { 
    ... 
}); 

我用JQ VS 1.10.2

+0

可能重复[如何让jQuery的1.7。对()悬停?](http://stackoverflow.com/questions/11541754/how-to-make-jquery-1- 7-on-hover)和http://stackoverflow.com/questions/9827095/is-it-possible-to-use-jquery-on-and-hover – j08691

+0

谢谢,这很有帮助! – user850690

回答

0

尝试添加mouseentermouseleave事件与on()。 这里是例子:

$(function(){ 
    $("#parent").on({ 
     mouseenter : function(e){ 
      alert("Mouse enter"); 
     }, 
     mouseleave : function(e){ 
      alert("Mouse leave"); 
     } 
    }, ".child"); 
}); 

的jsfiddle:http://jsfiddle.net/ashishanexpert/2XG9j/

3

如果是动态生成的整个div#parent块,你可能需要您的hover监听器绑定到文档本身,如下所示。

此外,我建议使用mouseentermouseleave听众,因为hover简写在jQuery 1.9中被删除。

在jQuery 1.8中不赞成使用,在1.9中删除:名称“hover”用作字符串“mouseenter mouseleave”的 的简写形式。

这里是我的示例:

jQuery(document).on('mouseenter', '#parent .child', function (e) { 
    jQuery(this).css('backgroundColor','#F00'); 
}).on('mouseleave', '#parent .child', function (e) { 
    jQuery(this).css('backgroundColor','#FFF'); 
}); 

http://jsfiddle.net/UX8z5/1/

0

您可以使用.hover()方法结合处理两种的mouseenter和鼠标离开事件。您可以使用它在鼠标位于元素内时简单地将行为应用于元素。

$(document).ready(function(){ 
    $('#parent .child').hover(function(){ 
    alert("Hello"); 
    }); 
}); 

Try in .hover() in Jsfiddle

您还可以使用.mouseover()事件。

$(document).on('mouseover', '#parent .child', function(){ 
    alert("Hello"); 
}); 

Try mouseover event handler fiddle

但这里的最佳实践结合mouseentermouseleave事件与事件委托。

$(document).ready(function(){ 
    $('#parent').on({ 
     mouseenter: function() { 
      alert('Hello'); 
     }, 
     mouseleave: function() { 
      alert('bye..!!!'); 
     } 
    }, ".child"); 
}); 

Try in fiddle

相关问题