jquery动态添加元素,报错。请问这个问题怎么处理。

yyxu123 2015-10-09 11:42:17
firebug 提示错误如下。HierarchyRequestError: Node cannot be inserted at the specified point in the hierarchy
我的目的是想动态的做一棵树。


<html>
<head>
<script type="text/javascript" src="https://ss1.bdstatic.com/5eN1bjq8AAUYm2zgoY3K/r/www/cache/static/protocol/https/jquery/jquery-1.10.2.min_f2fb5194.js"></script>
</head>
<body>
<div id="nestable_dep" class="nestable-white dd"></div>


<script type="text/javascript">
jQuery(document).ready(function() {
var Depelm = $("#nestable_dep");

var data=[{"SystemUsers":[],"Id":1,"Code":"123","Name":"123","ParentId":1,"Description":"","State":1},{"SystemUsers"
:[],"Id":2,"Code":"1232","Name":"123","ParentId":1,"Description":"","State":1},{"SystemUsers":[],"Id"
:3,"Code":"12321","Name":"1231","ParentId":2,"Description":"","State":1},{"SystemUsers":[],"Id":4,"Code"
:"2343","Name":"2343","ParentId":2,"Description":"","State":1},{"SystemUsers":[],"Id":5,"Code":"222"
,"Name":"222","ParentId":2,"Description":"","State":1},{"SystemUsers":[],"Id":6,"Code":"qwe","Name":"www"
,"ParentId":2,"Description":"","State":1}]

var dom = document.createElement("ol");
$(dom).addClass("dd-list");
Depelm.append(dom);

$.each(data, function(index, value) {

var item = document.createElement("li");
$(item).addClass("dd-item").attr("data-id", value.Id);
var itemDiv = document.createElement("div");
$(itemDiv).addClass("dd-handle").text(value.Name);
$(item).append(itemDiv);

var hasChild = Depelm.find("[data-id='" + value.ParentId + "']");
if (hasChild.length > 0) {
var cdol = $(hasChild[0]).children("ol:first");
if (cdol.length > 0) {
$(cdol[0]).append(item);
} else {
var cpol = $(hasChild[0]);
cpol.append(dom);
cpol.children("ol:first").append(item);
}
} else {
Depelm.children("ol:first").append(item);
}

});

});
</script>
</body>
</html>
...全文
293 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
天际的海浪 2015-10-11
  • 打赏
  • 举报
回复
你变量中存放的是页面元素对象的引用,一个元素对象只能放到一个地方,
append()是对元素对象的移动操作,而不是复制操作。
对同一元素对象多次用append()时,元素对象只会出现在最后一次的地方,之前的地方就没有了。
而你原来的代码是要把元素对象移动到它自身的体内。这当然是不可能的。
yyxu123 2015-10-11
  • 打赏
  • 举报
回复
@jslang

谢谢,你解决了我的问题。
js的变量不能复用么?我不太明白?
街头小贩 2015-10-10
  • 打赏
  • 举报
回复
问题出在append时的children("ol:first")
yyxu123 2015-10-10
  • 打赏
  • 举报
回复
引用 1 楼 xiaofanku 的回复:
问题出在append时的children("ol:first")
我知道问题出在这里,关键是怎么解决这个问题?
天际的海浪 2015-10-10
  • 打赏
  • 举报
回复
var hasChild = Depelm.find("[data-id='" + value.ParentId + "']"); if (hasChild.length > 0) { var cdol = $(hasChild[0]).children("ol:first"); if (cdol.length > 0) { $(cdol[0]).append(item); } else { var cpol = $(hasChild[0]); var dom2 = document.createElement("ol"); $(dom2).addClass("dd-list"); cpol.append(dom2); cpol.children("ol:first").append(item); } } else { Depelm.children("ol:first").append(item); }

87,923

社区成员

发帖
与我相关
我的任务
社区描述
Web 开发 JavaScript
社区管理员
  • JavaScript
  • 无·法
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧