2011-09-24 104 views
-2

我想要使用change事件侦听器更改value的值。可能吗?下面是我的示例代码:使用onchange更改变量值

<select name="select1" onchange="updatevariable(this.value)"> 
    <option value="2" >2</option> 
<option value="15" >15</option> 
</select> 
<script type="text/javascript"> 
    value = "test"; 
    function updatevariable(data) { 
     value = data;  
    } 
    alert(value); // It should be 2/15 
</script> 
+0

有什么问题?什么不行? –

+2

在您对选择字段进行任何更改(当您分配'value =“test”;'并定义'updatevariable',而不是*当您*调用updatevariable'时)'执行'alert'。把它放在事件处理程序中。 –

+0

是什么问题。它似乎工作正常http://jsfiddle.net/JmpSU/ –

回答

6

你在错误的地方

<select name="select1" onchange="updatevariable(this.value)"> 
    <option value="2" >2</option> 
    <option value="15" >15</option> 
</select> 
<script type="text/javascript"> 
    var value = "test"; 
    function updatevariable(data) { 
     value = data; 
     alert(value); 
    } 
</script> 

alert()在您的代码加载该文件的脚本被加载之后,
必须修改它是正确的叫改变后

+0

我可以在函数外使用'value'变量吗? –

+0

是的,但只有在调用'updatevariable'函数后才改变该值。 –

+0

这就是我想要的。你能举个例子吗? –