我极大地缩短了代码,但在下面很有效地传达了这一点,如果按钮被按下,我试图获取变量“ Monitor”进行更新。如果将所有代码放入“ button.onclick”函数中,则可以将变量传递到代码中。但是,直到按下按钮,我的代码才会运行。我需要运行我的代码,如果按下按钮,它将更新我的代码。
<form name="form1">
<span id="buttons">
<input type="button" name="button1" value="funny1"/>
<input type="button" name="button2" value="funny2"/>
</span>
</form>
<script type="text/javascript">
var Monitor, buttonsDiv=document.getElementById("buttons");
Monitor = "funny1"
for (var i=1; i<=2; i++) {
var button = document.form1["button" + i];
button.onclick = function() {
buttons.Monitor = this.value;
};
/*lots of my own code that runs
inside of my for loop waiting
to reference monitor for an update*/
</script>
最佳答案
希望以下代码可以使您朝正确的方向前进。我认为您没有尝试为每个按钮连接所有事件,而是尝试获取它,因此每个按钮将随后调用一个函数来设置Monitor的值。
var Monitor = "funny1";
//selecting all elements named button
var buttons = document.querySelectorAll('input[type="button"]');
//For each of the buttons wire up an event listener
for(var i=0, length=buttons.length; i < length;i++)
{
//create a reference shorthand
var button = buttons[i];
//add the event listener for a click
button.addEventListener('click', function(event)
{
//on the event look at the event's target property to find the element that invoked the click
Monitor = event.target.value;
console.log(Monitor); //Output the value of monitor the the console
});
}
此代码首先查找所有带有type = button的输入。我建议您也许给输入一个类,而不是使选择器更清晰,您的选择。其次,我遍历按钮并为每个按钮关联一个事件。然后,该事件将设置Monitor变量的值。
http://jsfiddle.net/wcf4c/