[英]Use JS var value only after a button click
I want to show which menu value was selected using JavaScript, like this: 我想显示使用JavaScript选择的菜单值,如下所示:
<script>
document.writeln(value);
</script>
Where the JS variable called value
gets defined by jQuery when a button is clicked: 单击按钮时,jQuery定义了名为
value
的JS变量:
$('#submit').click(function(){
var value = $('#model').val();
});
The problem being that the code tries to render value
before it has been created by the button. 问题在于代码试图在按钮创建
value
之前呈现value
。
I know I can show/hide a div
based on the button click, but even if the section with writeln
is hidden it still has the same problem. 我知道我可以基于按钮单击显示/隐藏
div
,但是即使隐藏了writeln
的部分,它仍然存在相同的问题。 I also need to be able to change my selection, click submit, and have the value update properly. 我还需要能够更改选择,单击提交,并正确更新值。
Here's a jsFiddle illustrating the problem: 这是一个说明问题的jsFiddle:
https://jsfiddle.net/f3n7uq14/4/ https://jsfiddle.net/f3n7uq14/4/
<span id="result"></span>
<script>
$('#submit').click(function(){
var value = $('#model').val();
$('#result').text(value);
});
</script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.