jQuery中hover和blur使用代理delegate无效的解决方法

今天就遇到了这样的小问题:

$(document).ready(function(){
$('.status_on').hover(function(){
$(this).html('点击禁用');
$(this).css('color','red');
},function(){
$(this).html('已激活');
$(this).css('color','green');
});
});



但是当需要触发hover的元素是js后来生成的时候,hover是无效的.
于是第一反应是想到用delegate代理:

 $(document).delegate('.status_on','hover',function(){
$(this).html('点击禁用');
$(this).css('color','red');
});
$(document).delegate('.status_on','blur',function(){
$(this).html('已激活');
$(this).css('color','green');
});


因为hover不是标准的事件,因此无法直接使用live和delegate进行处理

同理,blur也是.

知道了原因,解决方法就很简单了,用mouseenter和mouseleave替代hover和blur就行了:

$(document).delegate('.status_on','mouseenter',function(){
$(this).html('点击禁用');
$(this).css('color','red');
});
$(document).delegate('.status_on','mouseleave',function(){
$(this).html('已激活');
$(this).css('color','green');
});

原文地址:https://www.cnblogs.com/chessYu/p/7509473.html