2014-01-07 147 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

相關問題