10

使用 jQuery,我试图在悬停时替换这些链接内的文本,包括跨度。然后当用户悬停时,原始文本再次显示。

<a class="btn" href="#">
    <img src="#" alt=""/>
    <span>Replace me</span> please
</a>

<a class="btn" href="#">
    <img src="#" alt=""/>
    <span>Replace me</span> please
</a>

最终输出应该是

<a class="btn" href="#">
    <img src="#" alt=""/>
    I'm replaced!
</a>

我正在玩弄,但不知道如何将其更换回来。有任何想法吗?

$('.btn').hover(function(){
    $(this).text("I'm replaced!");
});
4

5 回答 5

25
$('.btn').hover(
    function() {
        var $this = $(this); // caching $(this)
        $this.data('defaultText', $this.text());
        $this.text("I'm replaced!");
    },
    function() {
        var $this = $(this); // caching $(this)
        $this.text($this.data('defaultText'));
    }
);

您可以将原始文本保存在data-defaultText存储在节点本身的属性中,以避免变量

于 2012-05-22T11:30:52.240 回答
4

这应该可以解决问题

$(function(){
  var prev;    

  $('.btn').hover(function(){
  prev = $(this).text();
      $(this).text("I'm replaced!");
  }, function(){
      $(this).text(prev)
  });
})
于 2012-05-22T11:31:01.467 回答
1
$('.btn').hover(function() {
    // store $(this).text() in a variable     
    $(this).text("I'm replaced!");
},
function() {
    // assign it back here
});
于 2012-05-22T11:31:39.363 回答
1

像这样向悬停事件添加另一个函数:

$('.btn').hover(function(){
    $(this).text("I'm replaced!");
}, function() {
    $(this).text("Replace me please");
});

演示链接

于 2012-05-22T11:33:22.580 回答
0

您需要将其存储在一个变量中才能将其设置回原来的样子,请尝试:

var text;

$(".btn").hover(function () {
    text = $(this).text();
    $(this).text("I'm replaced!");
},
function () {
    $(this).text(text);
});
于 2012-05-22T11:31:49.313 回答