使用 Javascript onClick 更改 div 内容

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

Changing div content with Javascript onClick

javascripthtmlformsgetelementbyid

提问by Benck

I'm trying to use a textbox and a submit button to change a div on the page. I want to take the text that has been typed in the textbox and put it in the div when the button is clicked. I have this code:

我正在尝试使用文本框和提交按钮来更改页面上的 div。我想把在文本框中输入的文本,当按钮被点击时,把它放在 div 中。我有这个代码:

function myfunction() { 
    var myText = document.getElementById("textbox").value;
    document.getElementById('myDiv').innerHTML = myText;
 } 
<form>
<input type="text" name="textbox" id="textbox" />
<input type="submit" name="button" id="button" onclick="myfunction()" />
</form>
<br/>
<div id="myDiv"></div>

But nothing happens. When I try it in the browser it just refreshes the page and adds ?textbox=someValueHereto the end of the URL. How can I get the div to display the textbox value?

但什么也没有发生。当我在浏览器中尝试它时,它只会刷新页面并添加?textbox=someValueHere到 URL 的末尾。如何让 div 显示文本框值?

回答by Dashsa

The problem is that the submit button is posting the form, so you are not seeing the change - If you change your submit button to a normal button it will work

问题是提交按钮正在发布表单,因此您没有看到更改 - 如果您将提交按钮更改为普通按钮,它将起作用

<input type="button"name="button" id="button" onclick="myfunction()" /> 

回答by Sterling Archer

Nothing happens because the form is being submitted. You need to prevent the default action from happening, which is the form submission. See preventDefault()or return falsein the MDN for more details on how to prevent an events default action from occurring.

没有任何反应,因为正在提交表单。您需要防止发生默认操作,即表单提交。有关如何防止事件默认操作发生的更多详细信息,请参阅MDN 中的preventDefault()return false

回答by Barmar

Call event.preventDefault()to prevent the normal form submission.

调用event.preventDefault()阻止正常的表单提交。

function myfunction(e) { 
    e.preventDefault();
    var myText = document.getElementById("textbox").value;
    document.getElementById('myDiv').innerHTML = myText;
 } 

<form>
<input type="text" name="textbox" id="textbox" />
<input type="submit" name="button" id="button" onclick="myfunction(event)" />
</form>
<br/>
<div id="myDiv"></div>

回答by User970008

The form is submitting. You need to stop that by adding return false; (if you are using Jquery) Or remove the form entirely it is not required.

表单正在提交。您需要通过添加 return false 来阻止它;(如果您使用的是 Jquery)或者完全删除不需要的表单。

function myfunction() { 
    var myText = document.getElementById("textbox").value;
    document.getElementById('myDiv').innerHTML = myText;
    return false;
 }