[英]Why is my button that calls a function on click making my page reload
I am working on a form that uses javascript to create a paragraph.我正在使用 javascript 创建段落的表单。 For some reason, when I click my button, it forces my page to reload.
出于某种原因,当我单击按钮时,它会强制我的页面重新加载。 Could you anyone let me know what I'm doing wrong here?
谁能让我知道我在这里做错了什么?
console.log('everything is linked') function createParagraph() { console.log('function called'); var wordOne=document.getElementById('textOne').value var wordTwo=document.getElementById('testTwo').value var paragraph = '<p>My first word is' + wordOne+'. My Second word is '+ wordTwo+'.</p>'; document.getElementById('answer').innerHTML= paragraph }
<body> <form action=""> <input id='textOne' type="text"> <input id='textTwo' type="text"> <button onclick="createParagraph()">Click Me</button> </form> <div id="answer"></div> <script src="app.js"></script> </body>
The default behavior of a <button>
inside a <form>
is to submit that form. <form>
中的<button>
的默认行为是提交该表单。 Set the button's type
to explicitly not be a "submit":将按钮的
type
设置为明确不是“提交”:
<button type="button" onclick="createParagraph()">Click Me</button>
Additionally, if you have no use for the actual <form>
(don't want to submit it) then it's probably best to just remove it:此外,如果您对实际的
<form>
没有用处(不想提交它),那么最好将其删除:
<body>
<input id='textOne' type="text">
<input id='textTwo' type="text">
<button type="button" onclick="createParagraph()">Click Me</button>
<div id="answer"></div>
<script src="app.js"></script>
</body>
That way there's nothing to accidentally be submitted in the first place.这样一开始就不会意外提交任何内容。
Your button acts as a submit button, so your form is being submitted.您的按钮充当提交按钮,因此您的表单正在提交。 To prevent this, you can use attribute onSubmit on your form and prevent sending form.
为了防止这种情况,您可以在表单上使用属性 onSubmit 并阻止发送表单。
<form onSubmit="return false">
Because the button is in a form and the form is probably submitted.因为按钮在表单中,并且表单可能已提交。
add the type="button"
to not submit the form.添加
type="button"
以不提交表单。
console.log('everything is linked') function createParagraph() { console.log('function called'); var wordOne=document.getElementById('textOne').value var wordTwo=document.getElementById('testTwo').value var paragraph = '<p>My first word is' + wordOne+'. My Second word is '+ wordTwo+'.</p>'; document.getElementById('answer').innerHTML= paragraph }
<body> <form action=""> <input id='textOne' type="text"> <input id='textTwo' type="text"> <button type="button" onclick="createParagraph()">Click Me</button> </form> <div id="answer"></div> <script src="app.js"></script> </body>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.