簡體   English   中英

jQuery切換按鈕文本和圖標

[英]jQuery toggle button text and Icon

我試圖在按鈕上切換圖標和按鈕文本,每個功能獨立工作,但連續運行時它們不起作用。 似乎切換按鈕文本的功能是完全刪除我的圖標。

<button type="button" id="toggle-list-details">
    <i class="fa fa-list fa-lg"></i> 
    List View
</button>
$("#toggle-list-details").click(function() {
    $(this).text(function(i, text){
        return text === " List View" ? " Details View" : " List View";
      });                                
    $(this).find('i').toggleClass('fa-list fa-th-list'); 
)};

當你這樣做

$(this).text(function(i, text){ 

this指的是<button type="button" id="toggle-list-details"> ,因此它用純文本替換所有內部內容。

為了避免這種情況,你可以像這樣做:

<button type="button" id="toggle-list-details">
    <i class="fa fa-list fa-lg"></i> 
    <span class="text">List View</span>
</button>

$("#toggle-list-details").click(function() {
    $(this).find('span').text(function(i, text){
        return text === " List View" ? " Details View" : " List View";
      });                                
    $(this).find('i').toggleClass('fa-list fa-th-list'); 
)};

暫無
暫無

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

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