jQuery 在悬停时替换元素的文本 [英] jQuery replace text of element on hover

查看:20
本文介绍了jQuery 在悬停时替换元素的文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

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

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

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

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

推荐答案

$('.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 属性中,以避免变量

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

这篇关于jQuery 在悬停时替换元素的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆