我有一个列表,当鼠标悬停在元素上时,我试图更改元素的文本。例如,如果我有这个列表
<ul>
<li id="first-li">Some text</li>
<li id="second-li">More text</li>
<li id="third-li">and more text</li>
</ul>
并且鼠标位于第一个元素上,我希望文本更改为,例如“第一个元素”。
我正在尝试使用以下代码实现上述目标:
$(document).ready(function(){
//when mouse is over, save initial value and replace with newText
function hover_in(newText){
console.log(newText);
var $this = $(this);
$this.data('initialText', $this.text());
$this.text(newText);
}
//when mouse is over, replace with initial value
function hover_out(){
var $this = $(this);
$this.text($this.data('initialText'));
}
$('#first-li').hover(function(){hover_in("NEW TEXT")}, hover_out);
});
我可以看到控制台中打印的 hover_in
'“NEW TEXT”参数中插入的值,但文本没有更改。
知道我做错了什么吗?
提前致谢!
最佳答案
您的问题是,您正在创建两个函数来尝试获取 $(this)
变量,该变量仅在 hover
函数中可用。
您必须将 $(this)
作为此函数的变量传递。
$(document).ready(function(){
//when mouse is over, save initial value and replace with newText
function hover_in(newText, $this){
console.log(newText);
$this.data('initialText', $this.text());
$this.text(newText);
}
//when mouse is over, replace with initial value
function hover_out($this){
$this.text($this.data('initialText'));
}
$('li').hover(
function(){
hover_in("NEW TEXT", $(this));
},
function() {
hover_out($(this));
});
});
关于javascript - jQuery - li 元素上的悬停功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28991909/