我在点击form
提交时尝试打开新页面。
当<form></form>
标记不存在时,此代码很有效。为什么?如何才能使用表单标签呢?
HTML
<form name="input">
<input id="Answer" name="Answer" value="" placeholder="something"/>
...
<input id="Answer" name="Answer" value="" placeholder="something"/>
<input type="submit" value="Submit" onclick="reload(this)"/>
</form>
JS
function reload(e) {
e.preventDefault();
// do somthing with inputs
window.open('new_page.html', '_self');
// window.location.href = 'new_page.html';
}
我同时尝试了window.open('new_page.html', '_self');
,window.location.href = 'new_page.html';
和e.form.preventDefault;
答案 0 :(得分:2)
简单的答案是你没有将event
传递给函数,如果你传入了HTMLInputElement
(带有this
变量)改为event
(并假设更正了HTML),其中包含:
<form name="input">
<input id="Answer" name="Answer" value="" placeholder="something"/>
<input id="Answer" name="Answer" value="" placeholder="something"/>
<input id="Answer" name="Answer" value="" placeholder="something"/>
<input type="submit" value="Submit" onclick="reload(event)" />
</form>
和
function reload(e) {
console.log(e);
e.preventDefault();
// do somthing with inputs
window.open('http://example.com/', '_self');
}
然后它就像你期望的那样工作。
但是,我个人不希望使用内联事件处理,而是使用不引人注目的JavaScript:
<form name="input" method="post" action="#">
<input id="Answer" name="Answer" value="" placeholder="something" />
<input id="Answer" name="Answer" value="" placeholder="something" />
<input id="Answer" name="Answer" value="" placeholder="something" />
<input type="submit" value="Submit" />
</form>
使用:
function reload (e){
e.preventDefault();
var win = window.open('http://example.com/', '_self');
}
var form = document.getElementsByName('input')[0];
form.addEventListener('submit', reload);