问题描述
我正在尝试将html片段(输入元素)动态插入到已经存在的div节点中.
I am trying to dynamically insert html fragment(input element) into an already existing div node.
我需要创建三个输入元素,因此我正在使用循环来创建它们并通过jquery对其进行初始化.我将创建的元素存储在名为htmlstr的变量中.
I need to create three input elements, so I am using a loop to create them and initialize them via jquery. I am storing the created elements in a variable called htmlstr.
var Buildstorecontents = function Buildstorecontents ()
{
var $parts_holder = $("#parts_holder");
var $htmlstr = "";
for(var i = 0; i < 3; i += 1)
{
$htmlstr += $("<input />", {
"type" : "text",
"class" : "",
"readonly" : true
}).append($("<br />"));
}
console.log($htmlstr);
$parts_holder.append($htmlstr);
}
Buildstorecontents();
问题是变量htmlstr不能保存创建的html节点,而不能保存[object object].我正在犯什么错误,以及执行此操作的其他可能方式?
The problem is the variable htmlstr isn't holding the created html node but rather [object object]. What is the mistake I am making and other possible ways to do this?
这就是我要实现的目标
<div id="parts_holder">
<input type="text" class="" readonly/><br />
<input type="text" class="" readonly/><br />
<input type="text" class="" readonly/><br />
</div>
推荐答案
您正在尝试将jQuery对象连接到字符串.这将不起作用,因为jQuery对象没有有用的toString
值.
You're trying to concatenate a jQuery object to a string. This won't work, because a jQuery object does not have a useful toString
value.
您需要创建一个空的jQuery集合,并为其添加元素,然后追加该集合.
You need to create an empty jQuery collection, add
the elements to that, and then append that collection.
var $html = $();
for(var i = 0; i < 3; i += 1)
{
$html = $html.add($("<input />", {
"type" : "text",
"class" : "",
"readonly" : true
})).add($("<br />"));
}
console.log($html);
$parts_holder.append($html);
这篇关于尝试操纵dom时,jQuery返回[object object]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!