【问题标题】:Javascript: Change button text change after clickJavascript:单击后更改按钮文本更改
【发布时间】:2020-03-26 00:26:18
【问题描述】:
我有一个关于在用户单击按钮后更改按钮文本的简单问题。
我希望单击按钮使文本在两个值之间切换:“更多”和“更少”。请注意,在第一次点击之前,它必须有值“更多”,点击之后必须有值“更少”:
<button class="btn btn-primary" type="button" data-toggle="collapse" data-target="#collapseExample" aria-expanded="false" aria-controls="collapseExample">
More
</button>
<div class="collapse" id="collapseExample">
<p>Test</p>
</div>
【问题讨论】:
标签:
javascript
html
twitter-bootstrap
【解决方案1】:
这可以通过以下方式使用 vanilla javascript 来实现:
/*
Fetch the buttom element
*/
const button = document.body.querySelector('[data-target="#collapseExample"]');
/*
Add click event listener where we will provide logic that updates the button text
*/
button.addEventListener('click', function() {
/*
Update the text of the button to toggle beween "More" and "Less" when clicked
*/
if(button.innerText.toLowerCase() === 'less') {
button.innerText = 'More';
}
else {
button.innerText = 'Less';
}
});
<button class="btn btn-primary" type="button" data-toggle="collapse" data-target="#collapseExample" aria-expanded="false" aria-controls="collapseExample">
More
</button>
<div class="collapse" id="collapseExample">
<p>Test</p>
</div>
【解决方案2】:
基本上,您可以将onclick 事件添加到引用函数的按钮:
<button class="btn btn-primary" type="button" data-toggle="collapse" data-target="#collapseExample" aria-expanded="false" aria-controls="collapseExample" onclick="changeText()">
More
</button>
然后,您准备更改文本的函数:
function changeText () {
if (this.innerText == "More") { // check if text inside is "More"
this.innerText == "Less"; // If so, change to "Less"
} else {
this.innerText == "More";
}
}