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
fill input text
提问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 defaultValue
property so that any form resetresets the value to the desired value.
您还需要设置该defaultValue
属性,以便任何表单重置都会将该值重置为所需的值。