使用JQuery设置di​​v的鼠标悬停属性

时间:2010-05-22 17:35:58

标签: javascript jquery

我想为div设置一个属性。我这样做了:

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

但是,上述方法无效,鼠标结束或移出时不会发出警报。

我也尝试了$('#row-img_1').attr();,我也无法使用它。

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

感谢大家的帮助。

4 个答案:

答案 0 :(得分:3)

您需要将事件函数绑定到元素。设置事件属性无效,因为只有在加载页面时才会解释它们。因此,您需要以不同的方式连接事件回调:

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

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

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

答案 1 :(得分:1)

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

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

或使用有效执行相同操作的jQuery悬停事件

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

 });

答案 2 :(得分:0)

事件被注册为作为属性传递的函数,如下所示:

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

另请注意on中缺少的onmouseover

答案 3 :(得分:0)

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