简体   繁体   中英

How can I make dependent variables respond and update in HTML/javascript?

I was hoping someone could help me out. I am modelling a (simple) nuclear reactor and have a number of variables which are dependent on other variables, and on user inputs.

In the below code, initially the Control Rod Height is set at 50%, but the user can move the control rods up and down in the limits of 0 to 100. Reactor temperature is directly dependent on the control rod height, but I can't get it to update.

The TEST button displays the updated Control Rod Height, but the TEMPERATURE button will only ever display the initial value (based on control rod height = 50).

Is it possible to make Reactor Temperature update as the user changes the height of the control rods?

Thank you!

HTML

<div id="game">
<button onClick = "IncCRH()">Increase Control Rod Height</button>
<button onClick = "DecCRH()">Decrease Control Rod Height</button>
<div id="result"></div>
<br>
<br>
<button onClick="test()">TEST</button>
<br>
<br>
<button onClick="ReacTemp()">TEMPERATURE</button>
</div>

Javascript

var ControlRodHeight = 50;
var ReactorTemperature = (250 + (ControlRodHeight*20));

function IncCRH(){
    user = ++ControlRodHeight;
    if (ControlRodHeight > 100)
    ControlRodHeight = 100;
}
function DecCRH() {
    user = --ControlRodHeight;
    if (ControlRodHeight < 0)
    ControlRodHeight = 0
}

function test(){
    alert (ControlRodHeight);
}

function ReacTemp(){
    alert (ReactorTemperature);
}

You have to manually recalculate the ReactorTemperature when you change ControlRodHeight:

function IncCRH(){
    user = ++ControlRodHeight;
    if (ControlRodHeight > 100) {
        ControlRodHeight = 100;
    }
    ReactorTemperature = (250 + (ControlRodHeight*20));
}

(Or call a function which is doing it, in order to not repeat the code.)

you need to change ReactorTemperature value in these functions to have updated value var ControlRodHeight = 50; var ReactorTemperature = (250 + (ControlRodHeight*20));

function IncCRH(){
    user = ++ControlRodHeight;
    if (ControlRodHeight > 100){
    ControlRodHeight = 100;
}
    ReactorTemperature = (250 + (ControlRodHeight*20));
}
function DecCRH() {
    user = --ControlRodHeight;
    if (ControlRodHeight < 0){
    ControlRodHeight = 0
}
ReactorTemperature = (250 + (ControlRodHeight*20));
}

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