简体   繁体   中英

Changing style in javascript on onclick

I want to make a few simple buttons that toggle color each time they are pressed. With a button press also some unique string needs to be passed to the server. Therefore on every button press I run two functions. My problem is that when I run this script, button changes color to red only for the period after the alert message Msg1 is displayed. When I answer OK to the Msg2, the color of the button reverts back to green. What am I doing wrong here?

<style>
.button { background-color: green; }
.buttonOn { background-color: red; }
</style>

<button id="r1" class="button" onclick="mF1(id)">Relay 1</button>

<script>

function mF1(btn) {
var property = document.getElementById(btn);
alert('Msg1: This is ' + property.className);
if (property.className == 'button')     
    { property.className = 'buttonOn' }
else 
    { property.className = 'button';  }
alert('Msg2: This is ' + property.className);
mF2(btn);            
}

function mF2(id) { window.location.href='?HVAC-' + id; }

</script>

You are using JavaScript to change the DOM.

Then you are setting location.href to a new value.

This causes a new page to load.

The new page does not have the modifications you made to the DOM.


You would need to write code that examines the query string when the page loads and sets the appropriate classes.

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