2012-07-25 73 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