I am iterating an array and creating a div on the fly as follows:
我正在迭代一个数组并在运行中创建一个div,如下所示:
$.each(item,function(k,item2) {
html = '<td><div id="test">'+item2.Name +'</div></td>'
//For just testing purpose , I am adding a div dynamically as:
$("#test").append("<div class='test class'></div>");
});
But finally when I browse the html page , the new div with class='test class' is not to be found at all. Is there anything which I am missing?
但最后当我浏览html页面时,根本找不到具有class ='test class'的新div。有什么我想念的吗?
Edit : In the html tag "html", there are multiple divs , and I want to append to a particular div by id
编辑:在html标签“html”中,有多个div,我想通过id追加到特定的div
Not exactly sure what the problem is : but after the html has been created , $("#test").append("<div class='test class'></div>");
works but appending using $(html).find() doesnt
不完全确定问题是什么:但是在创建html之后,$(“#test”)。append(“
2 个解决方案
#1
2
As element is not appended in the DOM, you can not access it using
$
selector. You can usehtml
variable holding element in the form ofstring
, content will not be thedocument
but you can access#test
element after wrapping it with$
由于元素未附加在DOM中,因此无法使用$ selector访问它。您可以以字符串的形式使用html变量保持元素,内容将不是文档,但您可以使用$包装后访问#test元素
$.each(item, function(k, item2) {
var html = '<td><div id="test">' + item2.Name + '</div></td>';
$(html).find('#test').append("<div class='test class'></div>");
});
#2
0
You are not creating the element with id "test" dynamically, you have just assigned in variable. please try the below code
您没有动态创建id为“test”的元素,您刚刚在变量中进行了分配。请尝试以下代码
$.each(item,function(k,item2) {
html = '<td><div id="test">'+item2.Name +'</div></td>';
$('any existing element class/id').html(html);
//For just testing purpose , I am adding a div dynamically as:
$("#test").append("<div class='test class'></div>");
});
#1
2
As element is not appended in the DOM, you can not access it using
$
selector. You can usehtml
variable holding element in the form ofstring
, content will not be thedocument
but you can access#test
element after wrapping it with$
由于元素未附加在DOM中,因此无法使用$ selector访问它。您可以以字符串的形式使用html变量保持元素,内容将不是文档,但您可以使用$包装后访问#test元素
$.each(item, function(k, item2) {
var html = '<td><div id="test">' + item2.Name + '</div></td>';
$(html).find('#test').append("<div class='test class'></div>");
});
#2
0
You are not creating the element with id "test" dynamically, you have just assigned in variable. please try the below code
您没有动态创建id为“test”的元素,您刚刚在变量中进行了分配。请尝试以下代码
$.each(item,function(k,item2) {
html = '<td><div id="test">'+item2.Name +'</div></td>';
$('any existing element class/id').html(html);
//For just testing purpose , I am adding a div dynamically as:
$("#test").append("<div class='test class'></div>");
});