简体   繁体   中英

Jquery works after second click then keeps working fine

Here is the script which is working fine but starts working on second click. It was supposed to work from first click.

function change_text() {
  var button = document.getElementById('toggle_button');
  if (button.innerHTML === "Edit") {
    button.innerHTML = "Save";
  } else {
    button.innerHTML = "Edit";
  }
}

Here is the html:

<h3 class="panel-title">
  <a class="accordion-toggle" data-toggle="collapse" data-parent="#tsAccordion" href="#tsCollapseOne;#tsCollapseTwo">
    <span class="pull-right" id="toggle_button" onclick="change_text()" style="text-decoration: underline; color: orange; text-align: center; font-size: 16px; margin-top: -54px"> Edit </span>
  </a>
</h3>

please help.

 function change_text() { var button = document.getElementById('toggle_button'); if (button.innerHTML === "Edit") { button.innerHTML = "Save"; } else { button.innerHTML = "Edit"; } } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <h3 class="panel-title"> <a class="accordion-toggle" data-toggle="collapse" data-parent="#tsAccordion" href="#tsCollapseOne;#tsCollapseTwo"> <span class="pull-right" id="toggle_button" onclick="change_text()" style="text-decoration: underline; color: orange; text-align: center; font-size: 16px; margin-top: -54px"> Edit </span> </a> </h3> 

You need to use trim() on button.innerHTML as button.innerHTML is giving you the value Edit with trailing and leading whitespaces. So, the condition button.innerHTML === "Edit" is false as it has trailing whilespace value with Edit . Thus, it executes the else block which replace the button.innerHTML with the value Edit without trailing and leading whitespaces. That is why it was working on second click as in second click the button.innerHTML value was Edit without whitespaces and if condition was true .

 function change_text() { var button = document.getElementById('toggle_button'); if (button.innerHTML.trim() === "Edit") { button.innerHTML = "Save"; } else { button.innerHTML = "Edit"; } } 
 <h3 class="panel-title"> <a class="accordion-toggle" data-toggle="collapse" data-parent="#tsAccordion" href="#tsCollapseOne;#tsCollapseTwo"> <span class="pull-right" id="toggle_button" onclick="change_text()" style="text-decoration: underline; color: orange; text-align: center; font-size: 16px; margin-top: -54px"> Edit </span> </a> </h3> 

Just remove extra spaces in your html before and after 'Edit' or use trim before comparing.

your function is being called on first time but it is comparing ' Edit ' with 'Edit' which result into false

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