在 html 文本框上显示一个 javascript 变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19312539/
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
Show a javascript variable on html textbox
提问by Alex
All I have to do is to show a number in a textbox and a button which add 10 every time I press it, here's my code (it doesn't work).
我所要做的就是在文本框中显示一个数字和一个按钮,每次按下它时都会增加 10,这是我的代码(它不起作用)。
<head>
<script type="text/javascript">
var n=parseInt(ocument.forms["formNum"]["numero"].value);
document.getElementById("numero").value=n;
function sumar() {
n=document.forms["formNum"]["numero"].value+10;
document.forms["formNum"]["numero"].value=n;
}
function inicializar() {
n=document.forms["formNum"]["numero"].value=0;
}
</script>
</head>
<body>
<form name="formNum">
<p>
<input type="text" size="10" name="numero" id="numero" />
</p>
<p>
<input type="button" name="sumar" value="Sumar" onclick="sumar()" />
<input type="button" name="inicializar" value="Iniciar a 0" onclick="inicializar()" />
</p>
</form>
</body>
回答by thefourtheye
<body>
<script type="text/javascript">
function sumar(){
document.getElementById("numero").value = parseInt(document.getElementById("numero").value)+10;
}
function inicializar(){
document.getElementById("numero").value=0;
}
</script>
<form name="formNum">
<p>
<input type="text" size="10" name="numero" id="numero" value="0" />
</p>
<p>
<input type="button" value="Sumar" onclick="sumar()" />
<input type="button" value="Iniciar a 0" onclick="inicializar()" />
</p>
</form>
</body>
Five suggestions.
五点建议。
- It is always better to give unique ids to your html elements.
- Never name your HTML elements and javascript functions the same.
- If you want to access the html element from javascript, if you know the id, use
getElementById
. - Use Firebug or Developer tools from the browser, to debug.
- If you want to access your elements with the hierarchy, use
elements
in the form like thisdocument.forms["formNum"].elements["numero"].value
. Check this example
- 为您的 html 元素提供唯一的 id 总是更好。
- 永远不要将您的 HTML 元素和 javascript 函数命名为相同的名称。
- 如果您想从 javascript 访问 html 元素,如果您知道 id,请使用
getElementById
. - 使用浏览器中的 Firebug 或开发人员工具进行调试。
- 如果要访问具有层次结构的元素,请使用
elements
像这样的表单document.forms["formNum"].elements["numero"].value
。检查这个例子
回答by HasanAboShally
This code should work:
此代码应该工作:
<input type="text" id="mytext">
<script type="text/javascript">
var elem = document.getElementById("mytext");
elem.value = "My default value";
</script>
See: Set the value of an input field
请参阅:设置输入字段的值
Maybe you are getting an exception from the parseInt
that prevents the value from changing.
也许您正在从parseInt
阻止值更改的异常中获取。