[英]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.