JQuery - 使用hover()和on()

时间:2012-07-25 20:11:31

标签: jquery

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

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

谢谢!

7 个答案:

答案 0 :(得分:5)

.hover实际上只是一个快捷方式而不是真正的事件名称。对于第一个函数,它只会扩展为mouseenter,而对于第二个函数,它会扩展为mouseleave

因此,您可以分别使用.on("mouseenter", "...",.on("mouseleave", "...",

答案 1 :(得分:2)

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

这是在不使用hover快捷方式的情况下委派$.hover()个事件的正确方法

答案 2 :(得分: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.

答案 3 :(得分:1)

这就是好消息: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);
});

答案 4 :(得分:1)

一个简单的例子:

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

<强> jsFiddle example

答案 5 :(得分:0)

var playerValue;

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

请查看this问题了解详情。由于playerValue超出了事件的范围,因此它将具有持续的值。根据您的脚本,这可能会有效,具体取决于是否可以一次鼠标悬停在多个.selector元素上。

答案 6 :(得分: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/