【问题标题】:Changing text onhover using jQuery使用 jQuery 更改悬停时的文本
【发布时间】:2015-10-10 19:15:07
【问题描述】:

我有一个 div,其中包含文本“one”。当您将鼠标悬停在它上面时,我想将文本更改为“二”,当您停止将鼠标悬停在它上面时,我想将文本更改回“一”。我尝试使用 jQuery 来做到这一点,但是在它变成“二”之后,一旦你停止将鼠标悬停在它上面,它就不会变回“一”。我做错了什么?

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("p").hover(function(){
        $(this).replaceWith("two");
        }, function(){
        $(this).replaceWith("one");
    });
});
</script>

<p>one</p>

【问题讨论】:

标签: javascript jquery html css


【解决方案1】:

使用text(),因为replaceWith() 将替换整个元素,并且您将其替换为文本而不是元素,因此下次选择元素会丢失。

$(document).ready(function(){
    $("p").hover(function(){
        $(this).text("two");
        }, function(){
        $(this).text("one");
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>


<p>one</p>

【讨论】:

  • 这怎么行不通? $(this).text("two").fadeIn(3000);
  • 因为它已经可见了!也许淡出()?或尝试$(this).text("two").hide().fadeIn(777);
  • @Anonymous0day 哈!所以,隐藏它,然后让它淡入!聪明!
【解决方案2】:

$(document).ready(function(){
    $("p").hover(function(){
        $(this).html("two");
        }, function(){
        $(this).html("one");
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>


<p>one</p>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-10
    • 2013-01-03
    • 2012-06-10
    • 2014-08-12
    • 2019-03-07
    相关资源
    最近更新 更多