繁体   English   中英

将输入元素附加到表单的正确方法

[英]the correct way to append an input element to a form

到目前为止,任何时候我都需要将输入动态添加到表单中,我已经完成了:

 var row = "<input type='text' id='someId' name='someName' value='someValue'>";
 $('#form').append(row);

我知道有更好的方法。 我已经阅读了有关setAttribute或.attr()的信息。 我将如何开始?

 var input = ???;
  input.attr('type','text');
  input.attr('id','someId');
  input.attr('name','someName');
  input.attr('val','someValue');
  input.attr('type','text');

 $('#form').append(input);

是的,存在更好的方法,

 $('#form').append($("<input>",{
   "type" : "text",
   "id" : "someId",
   "name" : "someName",
   "value" : "someValue"
 }));

不要将纯jquery与javascript混淆。 有时可能会导致错误。 例如在节点对象上调用jquery函数。 例如: node.css(...)

当我需要动态添加元素时,请执行以下操作:

var $_form = $("#form");
$("<input/>",{ id : "input_1",type : "text", val : "value" }).addClass("class1 class2").appendTo($_form);

此表单适用于任何元素,而不仅限于表单字段。

为简便起见,您只需一行即可完成以下操作:

$('#form').append("<input type='text' id='someId' name='someName' value='someValue'>");

但是对于更复杂的情况,您可以采用更长的方法:

$("<input/>", {
    attributes
});

您可以使用JavaScript的createElement()setAttribute()进行此操作 ,如下所示:

var input = document.createElement("input");
input.setAttribute("type", "text");
//and so on

正如@scottmarcus指出的那样,这不一定更好,但有所不同。 您正在寻找的是:

var input = document.createElement("INPUT");

这是一个DOM元素; 因此您不能使用jQuery方法,例如.attr() 您将必须使用JavaScript方法,例如setAttribute() 为了使用jQuery方法,您要做的就是将输入包装在$如下所示:

var input = $( document.createElement("INPUT") );

更好的写法是:

var input = $('<input/>');

参考: https : //developer.mozilla.org/zh-CN/docs/Web/API/Document/createElement

暂无
暂无

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

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