jQuery中有没有一种方法可以动态创建和提交表单.

Something like below.

<html>
    <head>
    <title> Title Text Goes Here </title>
    <script src="http://code.jquery.com/jquery-1.7.js"></script>
    <script>
        $(document).ready(function(){alert('hi')});
        $('<form/>').attr('action','form2.html').submit();
    </script>
    </head>
    <body>

        Content Area

    </body>
    </html>

Is this supposed to work or there is a different way to do this?

推荐答案

There were two things wrong with your code. The first one is that you included the $(document).ready(); but didn't wrap the jQuery object that's creating the element with it.

The second was the method you were using. jQuery will create any element when the selector (or where you would usually put the selector) is replaced with the element you wish to create. Then you just append it to the body and submit it.

$(document).ready(function(){
    $('<form action="form2.html"></form>').appendTo('body').submit();
});

Here's正在运行的代码.在本例中,它不会自动提交,只是为了证明它会添加表单元素.

Here's具有自动提交功能的代码.一切都很顺利.Jsfiddle将您带到一个404页面,因为"form2.html"显然不存在于其服务器上.

Jquery相关问答推荐

当一个很长的活动增加标题时,满历js每周都会出现.这是一种让标题只出现一次的方法吗?

使用动态类名的gm_addStyle?

使用 howler.js 中的变量播放多种声音

如何在光滑的轮播上添加进度条

可以推迟 jQuery 的加载吗?

jQuery:在mousemove事件期间检测按下的鼠标按钮

缺少 .map 资源?

在 div 中找到第一次出现的类

如何在 jquery 中包含 !important

如何 Select 具有特定文本的所有锚标记

jQuery $(document).ready () 触发两次

如何通过 Select 插件使用 jQuery 验证?

lodash debounce 在匿名函数中不起作用

scrollIntoView 是否适用于所有浏览器?

如何在 jQuery .each() 的每次迭代之间添加暂停?

jQuery .load() 调用不会在加载的 HTML 文件中执行 JavaScript

在 jquery 中启用/禁用下拉框

用 Javascript 加载 jQuery 并使用 jQuery

JQuery - 如何根据值 Select 下拉项

在 jQuery 中 Select 后代元素的最快方法是什么?