2012-07-25 74 views
1

我尝试使用jquery的on() - 方法与hover()的组合。我希望用户悬停在一个div上,获得一个值显示,并将鼠标从该div移开时再次看到旧值,但这不起作用......有人有线索吗?jQuery - 使用悬停()和()

$('#content').on('hover', '.player_marktwert_box', 
    function() { 
    var playerValue = $(this).html(); 
     $(this).html("test"); 
    }, 
    function() { 
     $(this).html(playerValue); 
    } 
); 

谢谢!

+0

看起来像它的弃用:http://api.jquery.com/on/ – 2012-07-25 20:15:49

回答

0
var playerValue; 

$(".selector").on({ 
    mouseenter: function() { 
     playerValue = $(this).html(); 
     $(this).html("test"); 
    }, 
    mouseleave: function() { 
     $(this).html(playerValue); 
    } 
}); 

请查看this问题了解更多详情。由于playerValue不在事件范围内,因此它的值将保持不变。根据您的脚本,这可能会起作用,具体取决于是否可以一次将鼠标放在多个.selector元素上。

5

.hover实际上只是一个快捷方式,而不是一个真正的事件名称。第一个功能扩展到mouseenter,第二个功能扩展到mouseleave

所以,你可以分别使用.on("mouseenter", "...",.on("mouseleave", "...",

+0

谢谢,但是我怎么才能在“mouseleave”中使用div的“old”值呢? – Torben 2012-07-25 20:15:30

+0

@Torben:您可以使用元素上的'.data'存储和检索它。 (你当前的代码不会共享变量'playerValue') – pimvdb 2012-07-25 20:16:19

2
$('#content').on({ 
    mouseenter: function() { ... }, 
    mouseleave: function() { ... } 
},'.player_marktwert_box'); 

这是委托hover事件,而无需使用$.hover()快捷

+0

+1,在这里使用一个对象是整洁的。 – pimvdb 2012-07-25 20:16:58

1

试试这个(只是根据pimvdb的想法)的正确方法

$('#content').on('mouseenter', '.player_marktwert_box', function() { 
    var playerValue = $(this).html(); 
    $(this).html("test").data('playerValue',playerValue); 
}).on('mouseleave', '.player_marktwert_box', function() { 
    $(this).html($(this).data('playerValue')); 
}); 

DEMO.

1

HERE是FIDDLE:http://jsfiddle.net/collabcoders/ses7G/

var originalValue; 
$('#content').on('mouseenter', '.player_marktwert_box', function(){ 
    originalValue = $(this).html(); 
    $(this).html("test"); 
}).on('mouseleave', '.player_marktwert_box', function() { 
    $(this).html(originalValue); 
}); 

0

有什么理由不只是使用.hover?

var playerValue = $('.player_marktwert_box').html(); 
$('.player_marktwert_box').hover(
    function() { 
     $(this).html("TEST :)"); 
    }, 
    function() { 
     $(this).html(playerValue); 
    } 
); 

DEMO - http://jsfiddle.net/M93mM/1/

+0

我可以看到Torben是否有多个.player_marktwert_box div实例的唯一原因。 – johnnyarguelles 2012-07-25 20:26:45

+0

有一个封装与.on是最好的做法,因为你不会初始化.player_martwer_box的每个实例 – johnnyarguelles 2012-07-25 20:27:42

+0

是的,我有该div的多个实例。 – Torben 2012-07-25 20:49:02

1

一个简单的例子:

var val=$('#foo').html(); 
$(document).on('mouseenter mouseleave', '#foo', function(ev) { 
    $(this).html((ev.type == 'mouseenter') ? 'test' : val); 
});​ 

jsFiddle example