2 回答

TA貢獻1798條經驗 獲得超7個贊
這是解決方案:-
<form onsubmit="event.preventDefault()">
<p>Enter Title Text:</p>
<div class="title"></div>
<input type="text">
<button onclick="hello()">Submit</button>
</form>
function hello() {
document.querySelector(".title").innerHTML =
document.querySelector("input").value;
}
首先,您需要通過使用 preventDefault 來防止表單的默認行為,或者只是省略表單標記,它在兩種情況下的工作方式相同,以便使用按鈕
的“onclick”事件 然后,為了獲得所需的結果,您可以使用innerHTML,就像我在這里使用的那樣。

TA貢獻1854條經驗 獲得超8個贊
將按鈕的類型更改為“按鈕”,因此單擊它不會提交表單。表單中按鈕的默認類型是“提交”,這將導致它提交表單,從而在單擊頁面時重新加載頁面。顯式設置類型可防止此行為。
請參見:https://developer.mozilla.org/en-US/docs/Web/HTML/Element/button
<button type="button" onclick="hello()">Submit</button>
function hello() {
document.querySelector("#result").textContent = "Title text is: " + document.querySelector("input").value;
}
<form>
<p>Enter Title Text:</p>
<input type="text">
<button type="button" onclick="hello()">Submit</button>
</form>
<p id="result">
</p>
添加回答
舉報