Javascript 使用 onchange 更改变量值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7538136/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 02:38:36  来源:igfitidea点击:

Change variable value using onchange

javascript

提问by no_freedom

I want to change the value of valueusing a changeevent listener. Is it possible? Here is my sample code:

我想更改value使用change事件侦听器的值。是否可以?这是我的示例代码:

<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>

回答by Marek Sebera

You have alert()in wrong place

alert()在错误的地方

<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>

In your code it is loaded right after the script is loaded,
you have to modify it to be called right after change

在您的代码中,它在脚本加载后立即加载,
您必须修改它才能在更改后立即调用