我正在尝试使用Jquery在div中动态创建div。当我为div1转储子节点时,它只显示文本和强。我期待'div1'有main_div_elem child和main_div_elem有col_md_8_elem孩子。
有人可以帮我添加col_md_8_elem作为main_div_elem和main_div_elem的孩子作为'div1'的孩子吗?
NodeList [#text“Here”,]
var id = 1;
function tryThis() {
$( "#div1" ).append( "<strong>Hello</strong>" );
var main_div_elem = $('<div /', {id : 'main_div_elem'.concat(id), "class" : "row"});
var col_md_8_elem = $('<div /', {id : 'col_md_8_elem'.concat(id), "class" : "col-md-8"});
main_div_elem.append(col_md_8_elem);
$('#div'.concat(id)).append(main_div_elem);
var children = document.getElementById("div1").childNodes;
console.log(children);
}
尝试使用jquery实现以下HTM代码。
<div class="row">
<div class="col-md-8">
</div>
</div>
谢谢, 迪帕克
答案 0 :(得分:0)
您的main_div_elem
和col_md_8_elem
未正确创建。 $(..)
调用的第一个参数是无效的HTML。您需要添加一个结束尖括号(>
),如下所示:
var id = 1;
function tryThis() {
$("#div1").append("<strong>Hello</strong>");
var main_div_elem = $('<div />', {
id: 'main_div_elem'.concat(id),
"class": "row"
});
var col_md_8_elem = $('<div />', {
id: 'col_md_8_elem'.concat(id),
"class": "col-md-8"
});
main_div_elem.append(col_md_8_elem);
$('#div'.concat(id)).append(main_div_elem);
var children = $("#div1").html();
console.log(children);
}
$(function() {
tryThis();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="div1"></div>
答案 1 :(得分:0)
你好你可以试试下面的代码。我用不同的方式写,但希望它会帮助你
$(document).ready(function() {
var id = 1;
var main_div_elem = "<div id=main_div_elem class='row'></div>"
var main_div_elem8 = "<div id='col_md_8_elem' class='col-md-8'></div>"
$("#div1").append(main_div_elem);
$("#main_div_elem").append(main_div_elem8);
var children = $("#div1").html();
console.log(children);
});
#div1 {
height: 100px;
width: 100px;
position: absolute;
padding: 10px;
background-color: red;
}
#main_div_elem {
height: 50px;
width: 50px;
position: absolute;
padding: 10px;
background-color: green;
}
#col_md_8_elem {
height: 20px;
width: 20px;
position: absolute;
padding: 10px;
background-color: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<div id="div1"></div>