javascript - jQuery - li 元素上的悬停功能

标签 javascript jquery text

我有一个列表,当鼠标悬停在元素上时,我试图更改元素的文本。例如,如果我有这个列表

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

相关文章:

javascript - 如何使用模板引用?

javascript - CSS 移动导航下拉菜单 - 对齐

javascript - 附加生成器 : ContentScript and back to Addon code?

text - 使用fabric.js在 Canvas 上绘制文本

javascript - Onload 单选选项无法正常工作

javascript - 动态添加数据属性

javascript - 如何使用 bootstrap 或 js 折叠 div 并打开选项卡

jQuery 在另一个包含文本的元素中添加一个元素

c# - WinForms:即时更改列表框文本颜色的最简单方法?

javascript - 如何过滤 Mongoose 中的日期事件?