[英]Why is my button that calls a function on click making my page reload
我正在使用 javascript 创建段落的表单。 出于某种原因,当我单击按钮时,它会强制我的页面重新加载。 谁能让我知道我在这里做错了什么?
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>
<form>
中的<button>
的默认行为是提交该表单。 将按钮的type
设置为明确不是“提交”:
<button type="button" onclick="createParagraph()">Click Me</button>
此外,如果您对实际的<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>
这样一开始就不会意外提交任何内容。
您的按钮充当提交按钮,因此您的表单正在提交。 为了防止这种情况,您可以在表单上使用属性 onSubmit 并阻止发送表单。
<form onSubmit="return false">
因为按钮在表单中,并且表单可能已提交。
添加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.