如何正确提交动态创建的表单与JS / jQuery? [英] How to properly submit a dynamically created form with JS/jQuery?

查看:100
本文介绍了如何正确提交动态创建的表单与JS / jQuery?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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();
});

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

预期行为:当点击搜索按钮时,页面应转到谷歌搜索。

Expected behavior: when clicking on the search button, page should forward to google search. Works as expected in latest Chrome, Safari and Opera.

在最新的FF和IE9中无法正常工作。

Does not work in latest FF and IE9. Clicking the button silently fails, no error messages, no forwarding happens.

我在这里缺少什么?

推荐答案

我没有参考任何特定的规范来支持为什么,但我相信它会工作,如果你追加新的形式到页面: / p>

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();
});

请注意,不要继续使用 .live ()在任何新的代码,因为它已从最新版本的jQuery中删除。而是使用:

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. 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+

(理想情况下指定更接近按钮的父元素,而不是 document 。)

(Ideally specifying a parent element closer to the button rather than document.)

这篇关于如何正确提交动态创建的表单与JS / jQuery?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆