开发者

Javascript: Changing variable on button click

I have a javascript file linked to index.html like below:

<script src='game.js' type='text/javascript'>
</script>

Assume that 开发者_JAVA百科game.js contains:

 var speed = ...;

Along with some other content.

I have 3 buttons on the HTML page that when clicked I want to change the variable speed in the javascript. Once clicked I want all 3 buttons to be disabled or hidden until the reset button is clicked. Any idea how I go about this?


Using pure HTML/JavaScript, here's what I would do:

<form name="form1">
  <span id="buttons">
    <input type="button" name="button1" value="Speed1"/>
    <input type="button" name="button2" value="Speed2"/>
    <input type="button" name="button3" value="Speed3"/>
  </span>
  <input name="reset" type="reset"/>
</form>
<script type="text/javascript">
  var speed, buttonsDiv=document.getElementById("buttons");
  for (var i=1; i<=3; i++) {
    var button = document.form1["button" + i];
    button.onclick = function() {
      speed = this.value;
      alert("OK: speed=" + speed);
      buttonsDiv.style.display = 'none';
    };
  }
  document.form1.reset.onclick = function() {
    speed = null;
    alert("Speed reset!");
    buttonsDiv.style.display = 'inline';
    return true;
  };
</script>

Here is a working example: http://jsfiddle.net/maerics/TnTuD/


Create functions within your javascript files that attach to the click events of each button.

The functions would change the variable you want.

aButtonelement.addEventListener('click',functionToChangeVariable,false)


Include the following in your Javascript file:

function DisableButtons() {
   speed = 100;
   document.getElementById("btn_1").disabled = true;
   document.getElementById("btn_2").disabled = true;
   document.getElementById("btn_3").disabled = true;
}

function EnableButtons() {
   document.getElementById("btn_1").disabled = false;
   document.getElementById("btn_2").disabled = false;
   document.getElementById("btn_3").disabled = false;
}

In your HTML, assign the following onClick events:

<button onClick="DisableButtons();">Button 1</button>
<button onClick="DisableButtons();">Button 2</button>
<button onClick="DisableButtons();">Button 3</button>    
<button onClick="EnableButtons();">Reset</button>


something like this? http://jsfiddle.net/qMRmn/

Basically, speed is a global variable, and clicking a button with the class set-speed class will set the speed to a new value, and disable all of the set-speed buttons. Clicking the reset button will re-enable them.

The code should be fairly self explanatory.


Easiest way, use jQuery.

$("#idofbutton").click(function () {
    // change variables here
});

Or you could register an event:

document.getElementById("idofbutton").addEventListener('click', function () {
    // change variables here
}, false);

Source

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜