输出消失了 Javascript simpleinnerHTML
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13765116/
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
Output disappeared Javascript simple innerHTML
提问by Martin Markovic
I am new to javascript and on every simple thing i get some kind of problem but this seems un-solve-able to me. I googled and nothing simillar.
我是 javascript 新手,在每件简单的事情上我都会遇到一些问题,但这对我来说似乎无法解决。我用谷歌搜索并没有类似的东西。
After i input data into textbox and store it into variable, i print out variable in paragraph. Problem is that output i printed out disappears within less than second. Code seems to be normal, what might it be? It looks like c when you dont put getch(); Thanks in advance.
在我将数据输入文本框并将其存储到变量中后,我在段落中打印出变量。问题是我打印出来的输出在不到一秒的时间内消失了。代码似乎很正常,可能是什么?当你不放 getch(); 时它看起来像 c; 提前致谢。
<form>Unesite broj koji ce se ispisat kasnije.<br>
<input type="text" id="userInput">
<input type="submit" name="unos" value="Unesi i ispisi" onclick="unesi()"><br><br>
</form>
<br><br>
<p>Unjeli ste <b id="ispis"></b></p>
<script>
function unesi(){
var userInput = document.getElementById('userInput').value;
document.getElementById('ispis').innerHTML = userInput;
}
</script>
回答by steveukx
The <form>
tag doesn't specify an action
attribute, so when you click the submit button, the browser will submit the form to the current URL - which will look a lot like the page is refreshing.
该<form>
标签未指定action
属性,因此当您单击提交按钮时,浏览器会将表单提交到当前 URL - 这看起来很像页面正在刷新。
If you want to run the unesi
function when the user clicks submit and prevent the HTML form from submitting, you need to change it slightly:
如果你想unesi
在用户点击提交时运行该功能并阻止HTML表单提交,你需要稍微改变它:
<input type="submit" name="unos" value="Unesi i ispisi"
onclick="unesi(); return false;">
The return false
prevents the form from submitting itself.
该return false
从自身提交防止形式。
回答by jonhopkins
Instead of cancelling the form submitting, another option is to change
而不是取消表单提交,另一种选择是更改
<input type="submit" name="unos" value="Unesi i ispisi" onclick="unesi()">
to
到
<input type="button" name="unos" value="Unesi i ispisi" onclick="unesi()">
This will make it so the form does not try to submit at all when the button is pressed.
这将使表单在按下按钮时根本不会尝试提交。
回答by epascarello
Because the form submits and refreshes the page. Cancel the form request.
因为表单提交并刷新页面。取消表单请求。
<input type="submit" name="unos" value="Unesi i ispisi" onclick="return unesi()">
and the function
和功能
function unesi(){
var userInput = document.getElementById('userInput').value;
document.getElementById('ispis').innerHTML = userInput;
return false;
}
better option is to do it on the form level
更好的选择是在表单级别进行
<form action="#" method="get" onsubmit="return unesi()">