我的任务是使用 jQuery 创建动态 form
。创建表单后,我需要将表单发送到 body
中声明的 div
标记。我在任何情况下都不允许在 HTML 正文中声明表单。表单在脚本中创建并显示在正文中。
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
在正文中声明为一个 div,上面的代码在本地脚本中。任何帮助或指点将不胜感激。
最佳答案
您需要将 frm
变量提供给 append()
方法,而不是为尚不在 DOM 中的元素提供字符串选择器,而不是提供给html()
方法,因为它需要一个字符串。试试这个:
var $frm = $("<form id=searchform></form>");
$frm.append(txt4, txt3, txt5, txt6);
$("#reports2").append($frm);
或者:
var $frm = $('<form id="searchform"></form>');
$frm.append(txt4, txt3, txt5, txt6).appendTo('#reports2');
以上两者在逻辑上是相同的,后者只是由于链式方法调用而更短。请注意变量名称前的 $
是一种命名约定,用于表示该变量包含一个 jQuery 对象。
关于javascript - 将表单附加到 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34929611/