cus*_*ice 9 jquery replace hover
使用jQuery,我试图在悬停时替换这些链接中的文本,包括span.然后,当用户将鼠标悬停时,将再次显示原始文本.
<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>
Run Code Online (Sandbox Code Playgroud)
最终的输出应该是
<a class="btn" href="#">
<img src="#" alt=""/>
I'm replaced!
</a>
Run Code Online (Sandbox Code Playgroud)
我正在四处寻找,但不知道如何更换它.有任何想法吗?
$('.btn').hover(function(){
$(this).text("I'm replaced!");
});
Run Code Online (Sandbox Code Playgroud)
fca*_*ran 23
$('.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'));
}
);
Run Code Online (Sandbox Code Playgroud)
您可以将原始文本data-defaultText保存在节点本身存储的属性中,以避免变量
这应该可以解决问题
$(function(){
var prev;
$('.btn').hover(function(){
prev = $(this).text();
$(this).text("I'm replaced!");
}, function(){
$(this).text(prev)
});
})
Run Code Online (Sandbox Code Playgroud)