2 回答
TA贡献1807条经验 获得超9个赞
一种方法是提供一个函数来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贡献1719条经验 获得超6个赞
您应该在 click 事件处理函数之外声明标志变量 ( 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>
添加回答
举报
