簡體   English   中英

使用jQuery更改文本onhover

[英]Changing text onhover using jQuery

我有一個帶有文本'one'的div。 當您將鼠標懸停在它上面時,我想將文本更改為“兩個”,當您停止將鼠標懸停在它上面時,我想將文本更改回“一個”。 我嘗試使用jQuery做到這一點,但在它變成'two'之后,一旦你停止在它上面,它就不會變回'one'。 我究竟做錯了什么?

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

使用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> 

 $(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> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM