我正在开发一个使用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>
发布于 2020-07-09 21:00:04
<form>中的<button>的默认行为是提交该表单。将按钮的type设置为显式不为"submit":
<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>这样一来,一开始就不会意外地提交任何东西。
发布于 2020-07-09 21:00:15
您的按钮充当提交按钮,因此您的表单正在被提交。为了防止出现这种情况,您可以在表单上使用attribute onSubmit并阻止发送表单。
<form onSubmit="return false">发布于 2020-07-09 21:03:04
因为按钮在表单中,并且表单可能已提交。
添加不提交表单的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>
https://stackoverflow.com/questions/62815349
复制相似问题