亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用 jQuery 在無限循環中單擊按鈕時更改按鈕的內容

使用 jQuery 在無限循環中單擊按鈕時更改按鈕的內容

吃雞游戲 2023-10-24 21:18:15
我想創建一個按鈕,在單擊時更改其內容,但當我再次單擊時,內容必須返回到其初始外觀。我已經成功創建了一個 jQuery 代碼,它更改了內容,但需要第二次單擊部分的幫助。我的目標是這個按鈕有兩個條件,并根據單擊時的活動條件切換到第二個條件。$("#changeArrow").click(function(){  var textShowing = true;  if (textShowing == true){    $("#changeArrow").html(function(){      return "This is some text! &otimes;";      textShowing = false;    });  }  else {    $("#changeArrow").html(function(){      return "This is some text! &oplus;";      textShowing = true;    });  }});<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><button id="changeArrow">This is some text! &oplus;</button>
查看完整描述

2 回答

?
qq_笑_17

TA貢獻1818條經驗 獲得超7個贊

一種方法是提供一個函數來html()檢查當前內容是什么并基于該內容返回新內容,如下所示:


$("#changeArrow").click(function() {

  $(this).html((i, h) => h == 'This is some text! ⊕' ? 'This is some text! ×' : 'This is some text! ⊕');

});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<button id="changeArrow">This is some text! &oplus;</button>


然而,由于您所做的只是更改圖標,因此如果您使用 CSS 添加圖標,這可能會變得更加簡單。然后你可以在每次點擊時簡單地切換一個類:


$("#changeArrow").click(function() {

  $(this).toggleClass('close');

});

#changeArrow:after {

  content: '⊕';

  margin: 0 -1px 0 4px;  

  display: inline-block;

}

#changeArrow.close:after {

  content: '×';

}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<button id="changeArrow">This is some text!</button>


查看完整回答
反對 回復 2023-10-24
?
滄海一幻覺

TA貢獻1824條經驗 獲得超5個贊

您應該在單擊事件處理函數之外聲明標志變量 ( textShowing )。此外,您可以使用this關鍵字來引用單擊的元素:


var textShowing = true;

$("#changeArrow").click(function(){

  if (textShowing == true){

    $(this).html("This is some text! &otimes;");

    textShowing = false;


  } else {

    $(this).html("This is some text! &oplus;");

    textShowing = true;

  }

});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<button id="changeArrow">This is some text! &oplus;</button>


查看完整回答
反對 回復 2023-10-24
  • 2 回答
  • 0 關注
  • 149 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號