简体   繁体   English

如何使用JS / jQuery正确提交动态创建的表单?

[英]How to properly submit a dynamically created form with JS/jQuery?

HTML: HTML:

<button class="search" name="search">search</button>

Javascript: Javascript:

$('button.search').live('click', function(event) {
    var newForm = jQuery('<form>', {
        'action': 'http://www.google.com/search',
        'target': '_top'
    }).append(jQuery('<input>', {
        'name': 'q',
        'value': 'stack overflow',
        'type': 'hidden'
    }));
    newForm.submit();
});

Fiddle: http://jsfiddle.net/YqGLH/90/ 小提琴: http : //jsfiddle.net/YqGLH/90/

Expected behavior: when clicking on the search button, page should forward to google search. 预期的行为:单击搜索按钮时,页面应转发到google搜索。 Works as expected in latest Chrome, Safari and Opera. 可在最新的Chrome,Safari和Opera中正常运行。

Does not work in latest FF and IE9. 在最新的FF和IE9中不起作用。 Clicking the button silently fails, no error messages, no forwarding happens. 无提示地单击该按钮将失败,不会出现错误消息,也不会发生转发。

What am I missing here? 我在这里想念什么?

I don't have a reference to any particular specification to support the why, but I believe it will work if you append the new form to the page: 我没有引用任何特定的规范来支持为什么,但是我相信,如果您将新表单附加到页面上,它将可以使用:

$('button.search').live('click', function(event) {
    jQuery('<form>', {
        'action': 'http://www.google.com/search',
        'target': '_top'
    }).append(jQuery('<input>', {
        'name': 'q',
        'value': 'stack overflow',
        'type': 'hidden'
    })).appendTo('body')
    .submit();
});

Note also that it would be a good idea not to keep using .live() in any new code, given that it has been removed from the latest version of jQuery. 还要注意,最好不要在任何新代码中继续使用.live() ,因为它已从最新版本的jQuery中删除。 Instead use: 而是使用:

$(document).on('click', 'button.search', function() {    // in jQuery v 1.7+   
// or
$(document).delegate('button.search', 'click', function() {    // in jQuery v 1.4.3+

(Ideally specifying a parent element closer to the button rather than document .) (理想情况下,指定一个更靠近按钮而不是document的父元素。)

It's also worth mentioning that you must add the form to the body element, not the document. 还值得一提的是,您必须将表单添加到body元素中,而不是文档中。 Chrome is forgiving and will work when the form is just added to the document element, but IE and Firefox will need you to add it to the body element specifically. Chrome是宽容的,并且仅在将表单添加到document元素时才可以使用,但是IE和Firefox将需要您将其专门添加到body元素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM