2010-05-22 59 views
0

我想为div设置一个属性。我已经做到了这一点:使用jQuery设置di​​v的属性使用jQuery

$('#row-img_1').onmouseover = function(){ alert('foo'); }; 
$('#row-img_2').onmouseout = function(){ alert('foo2'); }; 

然而,上面没有奏效,当鼠标移动到或当它移动了它不会发出警报。

我也尝试了$('#row-img_1').attr();,我也无法让这个工作。

我知道我应该使用更有效的事件处理系统,但我的div是动态生成的。另外这是一个小项目。 ;)

谢谢大家的帮助。

回答

1
$('#row-img_1').bind('mouseenter', function(event){ 
    // event handler for mouseenter 
}); 

$('#row-img_1').bind('mouseleave', function(event){ 
    // event handler for mouseleave 
}); 

或使用jQuerys悬停事件,您需要将事件函数绑定到的元素。设置事件属性不起作用,因为只有在加载页面时才解释它们。因此,你需要将事件回调连接以不同的方式:

$('#row-img_1').mouseover(function() { 
    alert('foo'); 
}); 
$('#row-img_2').mouseout(function() { 
    alert('foo2'); 
}); 

在jQuery中,有两个事件:mouseentermouseleave。这些是相似的,但mouseenter不会在将鼠标从子元素移动到主元素时触发,而mouseover将再次触发该事件。相同的逻辑适用于mouseleave vs mouseout

但是,jquery为这种用法提供了一个快捷方式:.hover方法。

+0

悬停为我工作!我将如何解除悬停?我尝试了'$('#row-img_1')。unbind('hover');'但它不起作用。 – Abs 2010-05-22 17:53:23

+0

感谢尼克斯评论,我解除了mouseenter和mouseleave的绑定,而不是平常的绑定。我可能已经从你的答案中解决了这个问题。谢谢jAndy。 – Abs 2010-05-22 17:56:11

+0

@Abs - ''.unbind('mouseenter mouseleave')':) – 2010-05-22 17:56:23

0

事件被注册为作为属性传递功能,如:

$('#row-img_1').mouseover(function(){ alert('foo'); }); 
$('#row-img_2').mouseout(function(){ alert('foo2'); }); 

另外,还要注意从onmouseover失踪on。其用途不同不相同

$('#row-img_1').hover(function(){ 
    // event handler for mouseenter 
}, function(){ 
    // event handler for mouseleave 

}); 
0
$('#row-img_1').mouseover(function() { 
    alert('foo'); 
}); 
+0

-1:我认为你的意思是'.mouseover',而不是'.onmouseover' – Eric 2010-05-22 17:50:20

+0

@Eric,是的,你是对的,这就是我的意思:-) – 2010-05-22 17:51:02

3

+1

+1 - 值得注意的是,这不是*等效*,但*与['.hover()'](http://api.jquery.com/hover/)相似。它映射到'mouseenter'和'mouseleave',而不是'mouseover'和'mouseout'。 – 2010-05-22 17:47:18

+0

好点。总之,'mouseenter'和'mouseleave'是这些应用程序所需要的,无论如何。 – Eric 2010-05-22 17:49:43

+0

@Nick - 知道这很有用! – Abs 2010-05-22 17:53:59