我试图使用event.prventDefault((来阻止页面刷新,但页面仍在刷新,并且不会显示警报。然而,当我将相同的代码放入JS Fiddle中时,代码运行良好。有什么问题???
const searchForm = document.getElementById("searchForm");
searchForm.addEventListener('submit', function(event) {
var topic = document.getElementById("topicSearch").value;
alert(topic);
event.preventDefault();
});
<form id="searchForm">
<input id="topicSearch">
<button type="submit">Search</button>
</form>
您可以试试这个。
document.addEventListener('readystatechange', function() {
if(document.readyState == 'complete') {
const searchForm = document.getElementById("searchForm");
searchForm.addEventListener('submit', function(event) {
var topic = document.getElementById("topicSearch").value;
alert(topic);
event.preventDefault();
});
}
})
<form id="searchForm">
<input id="topicSearch">
<button type="submit">Search</button>
</form>