简体   繁体   English

将表格附加到div

[英]Append form to div

I have been tasked with creating a dynamic form using jQuery. 我的任务是使用jQuery创建动态form Once I have created the form I need to send the form to a div tag declared in the body . 创建表单后,我需要将表单发送到body声明的div标签。 I am under no circumstances allowed to declare the form in the body of the HTML. 我决不允许在HTML主体中声明该表单。 The form is created in the script and displayed in the body. 表单在脚本中创建并显示在正文中。

var frm = $("<form id=searchform></form>");     
$("#searchform").append(txt4, txt3, txt5, txt6); // txt4 etc, are elements added to the form    
$("#reports2").html("#searchform");// SOMETHING NOT QUITE RIGHT HERE!

reports2 is declared as a div in the body, code above is in a script locally. reports2在主体中声明为div,上面的代码在本地脚本中。 Any help or pointers would be appreciated. 任何帮助或指针,将不胜感激。

You need to provide the frm variable to the append() method, not the string selector for the element which is not yet in the DOM, and not to the html() method as that expects a string. 您需要将frm变量提供给append()方法,而不是尚未在DOM中的元素的字符串选择器,也不应该将html()方法提供给期望字符串的html()选择器。 Try this: 尝试这个:

var $frm = $("<form id=searchform></form>");
$frm.append(txt4, txt3, txt5, txt6);
$("#reports2").append($frm);

Or alternatively: 或者:

var $frm = $('<form id="searchform"></form>');
$frm.append(txt4, txt3, txt5, txt6).appendTo('#reports2');

Both of the above are logically the same, the latter is just shorter due to the chained method calls. 两者在逻辑上是相同的,由于链接的方法调用,后者更短。 Note the $ before the variable name is a naming convention used to denote that the variable holds a jQuery object. 请注意,变量名前的$是一种命名约定,用于表示变量包含jQuery对象。

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

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