【问题标题】:jQuery replace text of element on hoverjQuery在悬停时替换元素的文本
【发布时间】:2012-05-28 21:22:20
【问题描述】:

使用 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!");
});

【问题讨论】:

标签: jquery hover replace


【解决方案1】:
$('.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 属性中,以避免变量

【讨论】:

  • 你在我之前 43 秒发布了这个,但有趣的是,当我点击发送时,我的互联网瞬间中断,我在发送时必须输入验证码
  • 个人,这个替换它,但是当鼠标熄灭时,它仍然保留新文本!
  • 注意html节点中的key必须是kebab-cases,本例中为:&lt;div class="btn" data-default-text="foobar"&gt;
【解决方案2】:

这应该可以解决问题

$(function(){
  var prev;    

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

【讨论】:

    【解决方案3】:

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

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

    Link 用于演示

    【讨论】:

    • 哇,现在我意识到我的速度有多慢......在这里使用 jsfiddle 链接是个坏主意:'(
    【解决方案4】:
    $('.btn').hover(function() {
        // store $(this).text() in a variable     
        $(this).text("I'm replaced!");
    },
    function() {
        // assign it back here
    });
    

    【讨论】:

      【解决方案5】:

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-07-18
        • 2019-01-11
        • 2014-11-04
        • 2015-05-18
        • 2011-10-02
        • 2011-10-10
        • 2018-09-20
        • 1970-01-01
        相关资源
        最近更新 更多