Javascript:Change按钮单击后文本更改

Javascript:Change按钮单击后文本更改,javascript,html,twitter-bootstrap,Javascript,Html,Twitter Bootstrap,我有一个简单的问题,关于在用户单击按钮后更改按钮的文本 我想点击按钮使文本在两个值之间切换:“更多”和“更少”。请注意,在第一次单击之前,其值必须为“更多”,单击之后,其值必须为“更少”: 更多 试验 这可以通过以下方式使用vanilla javascript实现: /* 获取buttom元素 */ const button=document.body.querySelector(“[data target=“#collapseExample”]”); /* 添加click事件侦听器,我们将

我有一个简单的问题,关于在用户单击按钮后更改按钮的文本

我想点击按钮使文本在两个值之间切换:“更多”和“更少”。请注意,在第一次单击之前,其值必须为“更多”,单击之后,其值必须为“更少”:


更多
试验


这可以通过以下方式使用vanilla javascript实现:

/*
获取buttom元素
*/
const button=document.body.querySelector(“[data target=“#collapseExample”]”);
/*
添加click事件侦听器,我们将在其中提供更新按钮文本的逻辑
*/
addEventListener('click',function(){
/*
更新按钮的文本,以便在单击时在“更多”和“更少”之间切换
*/
if(button.innerText.toLowerCase()=='less'){
button.innerText='More';
}
否则{
button.innerText='Less';
}
});

更多
试验


基本上,您可以向引用函数的按钮添加一个
onclick
事件:


更多
然后,准备函数以更改文本:

function changeText () {
  if (this.innerText == "More") { // check if text inside is "More"
    this.innerText == "Less";    // If so, change to "Less"
  } else {
    this.innerText == "More";
  }
}
可能重复的
function changeText () {
  if (this.innerText == "More") { // check if text inside is "More"
    this.innerText == "Less";    // If so, change to "Less"
  } else {
    this.innerText == "More";
  }
}