[英]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.