jQuery 在悬停时替换元素的文本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10701124/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 09:40:27  来源:igfitidea点击:

jQuery replace text of element on hover

jqueryhoverreplace

提问by cusejuice

With jQuery, I'm trying to replace the text, including the span, inside these links on hover. Then when the user hover's off, the original text is displayed again.

使用 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>

The final output should be

最终输出应该是

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

I'm toying around with but not sure how to replace it back. Any ideas?

我在玩弄,但不知道如何把它换回来。有任何想法吗?

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

回答by Fabrizio Calderan

$('.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'));
    }
);

you could save the original text in a data-defaultTextattribute stored in the node itself so to avoid variables

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

回答by Andrew Willis

This should do the trick

这应该可以解决问题

$(function(){
  var prev;    

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

回答by xyz

$('.btn').hover(function() {
    // store $(this).text() in a variable     
    $(this).text("I'm replaced!");
},
function() {
    // assign it back here
});

回答by optimusprime619

add another function to the hover event like this:

向悬停事件添加另一个函数,如下所示:

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

Linkfor demo

演示链接

回答by mattytommo

You'd need to store it in a variable in order to set it back to what it was, try:

您需要将它存储在一个变量中以将其设置回原来的状态,请尝试:

var text;

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