如何在悬停时更改文本,并在鼠标悬停时恢复为默认值


How to change text on hover and revert to default on mouse out?

我有一个div,它显示的计数如下:

如何将文本从0更改为任何单词?例如,当鼠标位于div上时,并在鼠标离开时恢复为0。

我试过这个代码,但没有用。

$('.post-fav a').bind('mouseenter',function() {
    var default_text = $(this).text();
    $(this).css({'background-position' : 'left bottom', 'color' : '#1871a4'});
    $(this).html('<?php _e('favorite','deluxe'); ?>');
});
$('.post-fav a').bind('mouseleave',function() {
    $(this).css({'background-position' : 'left top', 'color' : '#666'});
    $(this).text(default_text);
});

默认文本是可变的,每个元素都有特定的计数,当鼠标移到上面时,我需要某种方式来存储初始计数。。我不能在js中硬编码为0或任何其他计数。

您只需要使用悬停函数,第一个参数是mouseover,第二个参数是mouseout:

$('div').hover(
    function() { $(this).html('anyword'); },
    function() { $(this).html('0'); }
);

编辑:

var storedtext;
$('div').hover(
    function() { 
        storedtext = $(this).html();
        $(this).html('anyword'); 
    },
    function() { $(this).html(storedtext); }
);
$inittext=$('div').html;

然后就像幕府将军说的

$('div').hover(
function() { $(this).html('anyword'); },
function() { $(this).html($inittext); }
);

最好的方法是使用数据属性:

<div data-initial-value="0">
<script>
$('div').bind('mouseenter',function() {
  var default_text = $(this).text();
  $(this).css({'background-position' : 'left bottom', 'color' : '#1871a4'});
  $(this).html('<?php _e('favorite','deluxe'); ?>');
});
$('div').bind('mouseleave',function() {
  $(this).css({'background-position' : 'left top', 'color' : '#666'});
  $(this).text($(this).data('initialValue');
}); 
</script>