作者:yilande | 来源:互联网 | 2023-05-18 14:21
我有一个列表,我试图在鼠标悬停时更改元素的文本.例如,如果我有这个清单
- Some text
- More text
- and more text
并且鼠标在第一个元素上,我希望文本更改为,例如,"第一个元素".
我正在尝试使用此代码实现上述目的:
$(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" 参数中看到值insert,但文本不会改变.
我有什么想法我做错了吗?
提前致谢 !
1> Mario Araque..:
您的问题是您正在创建两个尝试获取$(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));
});
});