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

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

问题描述

使用jQuery,我试图在悬停的这些链接中替换文本,包括span。

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>

最后的输出应该是

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


推荐答案

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

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

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

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

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