2 回答

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

TA貢獻1824條經驗 獲得超5個贊
您應該在單擊事件處理函數之外聲明標志變量 ( textShowing )。此外,您可以使用this關鍵字來引用單擊的元素:
var textShowing = true;
$("#changeArrow").click(function(){
if (textShowing == true){
$(this).html("This is some text! ⊗");
textShowing = false;
} else {
$(this).html("This is some text! ⊕");
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! ⊕</button>
- 2 回答
- 0 關注
- 149 瀏覽
添加回答
舉報