Javascript 填充输入文本

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

fill input text

javascript

提问by Jean

How can I fill a text input with a value? I am trying this:

如何使用值填充文本输入?我正在尝试这个:

<input id="curso" maxlength="150" name="curso" size="40" type="text" 
    value="window.location.href.substring(91))" />

But that does not work.

但这不起作用。

回答by Mike Samuel

<input id="curso" maxlength="150" name="curso" size="40" type="text">

<script>
document.getElementById("curso").value =
document.getElementById("curso").defaultValue = window.location.href.substring(91);
</script>

You can't execute JavaScript from within an arbitrary HTML attribute. Only <script>elements and event handlers can contain JavaScript, so add a <script>that sets the value.

您无法从任意 HTML 属性中执行 JavaScript。只有<script>元素和事件处理程序可以包含 JavaScript,因此添加<script>设置值的 。

You also need to set the defaultValueproperty so that any form resetresets the value to the desired value.

您还需要设置该defaultValue属性,以便任何表单重置都会将该值重置为所需的值。