将输入值设置为 Javascript 变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31059824/
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-23 06:09:08  来源:igfitidea点击:

Set Input Value to Javascript Variable

javascripthtmlvariablesinput

提问by JakeTheSnake

Let's say I have a variable called x in javascript. How can I set the value of a text input (HTML) to that variable? For example:

假设我在 javascript 中有一个名为 x 的变量。如何将文本输入 (HTML) 的值设置为该变量?例如:

The value of the input will now be Swag

输入的值现在将是 Swag

<input type="text" value="Swag" />

But if I want the value to be a javascript variable? How do I do? Something like this? (I am just guessing, trying to make my point clear)

但是,如果我希望该值是一个 javascript 变量呢?我该怎么办?像这样的东西?(我只是猜测,试图阐明我的观点)

<input type="text" value="variable.x" />

回答by brso05

You can set it in your javascript code like:

您可以在您的 javascript 代码中设置它,例如:

<input id="myInput" type="text" value="Swag" />

<script>
    var test = "test";
    document.getElementById("myInput").value = test;
</script>