简体   繁体   中英

Toggle button back to default html

I'm trying to change the innerHTML of my button back to default. It works with changing the innerHTML the first time, but then I can't get it back to default.

I've tried using booleans to toggle back and forth, but my code just won't execute the second part of the function.

 function money() { var money = document.getElementById('money'); var text = "normal"; if (text == "normal") { money.innerHTML = "<h1>Let me ask you</h1><p>Does this work<p>"; text = "changed"; } else { money.innerHTML = "<h1>Money Laundering</h1><p>Click For More Info</p>"; text = "normal"; } } 
 <div id="practiceContainer"> <h1 id="practiceHeader">Practice Areas</h1> <div class="lawgrid"> <button class="practicesBox" id="money" onclick="money()"> <h1>Money Laundering</h1> <p>Click For More Info</p> </button> </div> </div> 

I expected my code to change back to default html, but it doesn't happen.

You set the text variable to "normal" at the beginning of the function, therefore when your code reaches your if logic, text will always be "normal" .

Consider simply moving the text variable outside of your function, so that it doesn't keep resetting with each click.

 var text = "normal"; var btnMoney = document.getElementById('money'); function money() { if (text == "normal") { btnMoney.innerHTML = "<h1>Let me ask you</h1><p>Does this work<p>"; text = "changed"; } else { btnMoney.innerHTML = "<h1>Money Laundering</h1><p>Click For More Info</p>"; text = "normal"; } } 
 <div id="practiceContainer"> <h1 id="practiceHeader">Practice Areas</h1> <div class="lawgrid"> <button class="practicesBox" id="money" onclick="money()"> <h1>Money Laundering</h1> <p>Click For More Info</p> </button> </div> </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