从文本字段中获取值并将其发布到 javascript 变量中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14562964/
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
Get value from text field and post it in a javascript variable
提问by Perocat
Possible Duplicate:
Why does jQuery or a DOM method such as `getElementById` not find the element?
I have this script:
我有这个脚本:
<script>
var dataoriginale = document.getElementById("savedataoriginale").value;
</script>
and this text field:
和这个文本字段:
<input name="savedataoriginale" id="savedataoriginale" type="text" value="testtest">
but when I try to print the javascript var
但是当我尝试打印 javascript var
<script>document.write(dataoriginale)</script>
I get undefined.
我得到未定义。
Why? How can I fix that?
为什么?我该如何解决?
回答by g.e.manor
it's cause you have 2 conflict js session before you get the value from the input
这是因为在从输入中获取值之前,您有 2 个冲突 js 会话
here is work option
这是工作选项
<input name="savedataoriginale" id="savedataoriginale" type="text" value="testtest">
<script>
var dataoriginale = document.getElementById("savedataoriginale").value;
document.write(dataoriginale);
</script>
回答by AlexStack
Most probably because the <script>is executed before the <input>. It happens because document.getElementById("savedataoriginale").valuereturns undefinedwhen the DOM is not parsed.
很可能是因为<script>是在<input>. 这是因为在未解析 DOM 时document.getElementById("savedataoriginale").value返回undefined。
To solve this, put your <script>tag after the <input>and make sure it doesn't run until the DOM is parsed. You may as well use the DOMContentLoaded event like this:
要解决此问题,请将您的<script>标记放在之后,<input>并确保它在解析 DOM 之前不会运行。你也可以像这样使用 DOMContentLoaded 事件:
document.addEventListener("DOMContentLoaded", function(){
var dataoriginale = document.getElementById("savedataoriginale").value;
alert( dataoriginale );
},false);
More info:
更多信息:
PS. you don't need to have both idand nameattributes on your <input>element. Name is deprecated. ID is enough.
附注。您不需要在元素上同时拥有idandname属性<input>。名称已弃用。身就够了。

