window.open不使用表单

时间:2013-08-04 22:47:20

标签: javascript window.open

我在点击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;

jsFiddle

1 个答案:

答案 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');
}

JS Fiddle demo

然后它就像你期望的那样工作。

但是,我个人不希望使用内联事件处理,而是使用不引人注目的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);

JS Fiddle demo