简体   繁体   中英

Text and font-awesome icon wont change on toggle

I am trying to change the text of a button when clicked and back to normal when clicked again. The button is using a font awesome icon so figured I would try using this.html instead of this.text, but for some reason it is not recognising the HTML I am indicating?

If I change the HTML on the else statement then it will change on click which is what makes me think it is an issue with it not recognizing my HTML.

I know it might be something really stupid but cant seem to figure it out.

  $(document).ready(function(){
  $("#submitbutton").on("click", function(){
    if($(this).html()=="View code <i class=\"fas fa-chevron-right fa-xs\"></i>")
    {
        $(this).html("Close code <i class=\"fas fa-chevron-right fa-xs\"></i>");
    } else {
        $(this).html("View code <i class=\"fas fa-chevron-right fa-xs\"></i>");
    }
})
});
      <div class="getcodebuttoncontainer">
         <button
         type="button"
         class="btn-primary"
         id="submitbutton"
         onclick="retrieveData()"
         >View code <i class="fas fa-chevron-right fa-xs"></i></button>
      </div>

It seems as if the only change is the text ( "View || Close ") so you can simply put that variable text in spans - one with a display: none styling and then on the click - toggle the visibility of each.

 $(document).ready(function(){ $("#submitbutton").on("click", function(){ $(this).find('span').toggle(); }) }); 
 #submitbutton span:nth-of-type(2) { display: none; } 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="getcodebuttoncontainer"> <button type="button" class="btn-primary" id="submitbutton" > <span>View</span> <span>Close</span> code <i class="fas fa-chevron-right fa-xs"></i> </button> </div> 

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