简体   繁体   中英

Javascript: Change button text change after click

I have a simple question about changing the text of a button after the user clicks it.

I would like the button click to cause the text to toggle between two values: "More" and "Less". Note that before the first click, it must have the value "More" and after the click the value "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>

This can be achieved using vanilla javascript via the following:

 /* 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>

Basically, you could add an onclick event to the button referencing to a function:

<button class="btn btn-primary" type="button" data-toggle="collapse" data-target="#collapseExample" aria-expanded="false" aria-controls="collapseExample" onclick="changeText()">
  More
</button>

Then, you prepare the function to change the text:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM