2 回答

TA貢獻1770條經驗 獲得超3個贊
你說你不能修改你的 HTML,所以這是我找到的解決方案。
您想要阻止表單提交。您可以通過以下方式做到這一點:
const myForm = document.querySelector('#registrar');
myForm.addEventListener("submit", function(evt) {
evt.preventDefault();
});
請參閱工作片段:
function addLi() {
var txtVal = document.getElementById('txtVal').value,
listNode = document.getElementById('invitedList'),
liNode = document.createElement("LI"),
txtNode = document.createTextNode(txtVal);
liNode.appendChild(txtNode);
listNode.appendChild(liNode);
}
const myForm = document.querySelector('#registrar');
myForm.addEventListener("submit", function(evt) {
evt.preventDefault();
});
<div class="wrapper">
<div>
<h1>Football</h1>
<p>A Fottball Competition App</p>
<form id="registrar">
<input type="text" id="txtVal" name="name" placeholder="Invite Team">
<button type="submit" onclick="addLi()" name="submit" value="submit">Submit</button>
</form>
</div>
<div class="main">
<h2>Invitees</h2>
<ul id="invitedList">
</ul>
</div>
</div>

TA貢獻1877條經驗 獲得超6個贊
您只需要更改html中的提交按鈕并為提交事件監聽器添加preventDefault
超文本標記語言
/* Replace the button to input as below */
<input type="submit" value="Submit">
JS
/* Adding eventlistener for the form submit */
const form = document.getElementById('registrar');
form.addEventListener('submit', addLi);
function addLi(e) {
/* Prevent the default functionality - in this case it is, reloading page */
e.preventDefault();
/*
...the rest of the function code
*/
}
如果有任何不清楚的地方,請隨時詢問。
- 2 回答
- 0 關注
- 124 瀏覽
添加回答
舉報