1

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

例如,当鼠标悬停在 div 上时,如何将文本从 0 更改为任何单词,并在鼠标离开时恢复为 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 或任何其他计数。

4

3 回答 3

5

你只需要使用hover功能,第一个参数是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); }
);
于 2012-07-13T20:44:08.490 回答
2
$inittext=$('div').html;

然后正如幕府将军所说

$('div').hover(
function() { $(this).html('anyword'); },
function() { $(this).html($inittext); }
);
于 2012-07-13T20:51:16.460 回答
1

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

<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>
于 2012-07-13T20:56:00.577 回答