0

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

4

1 回答 1

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 小提琴演示

然后它会按您的预期工作。

但是,我个人更喜欢不使用内联事件处理,而是使用不显眼的 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 小提琴演示

于 2013-08-04T23:23:57.937 回答