前提:
我想从文档中取出一大块 html,然后更改 div id 并在原始 html 下方的同一文档中重新打印相同的 html 块并进行一些修改。我会重复这个'X'次。
问题:
当我尝试重新打印时,我似乎无法访问 html 块中的 div。
我的脚步
我在一个页面上有一些 html,包含在一个 div 中,
<div id="a"> <div id="aaa">...</div> <div id="bbb">...</div> <div id="ccc">...</div> </div>
我使用 jQuery 提取这个 html
var h = $("#a").html();
我将它转换为 jQuery 对象
var jqObj = $(h);
然后查看里面的div
$("div", jqObj).each(function (idx, elem) {
//elem is a HTMLDivElement type
var jq = $(this);
// I want to access the id, class etc. of the div elements here
});
'each' 正确迭代的次数与 div 的次数一样多。
但无论我做什么,无论是 $(this).attr("id") 还是 elem.id 或其他任何东西,它都会返回未定义。我打印了 $(this).html() ,它似乎有内容,但是 div 中的所有 id 似乎都被删除了。
我究竟做错了什么?如何获取此 HtmlDivElement 的 id(我需要在再次打印出 html 之前更改它们)和其他属性?
问题解决了
请参阅下面有关使用 clone() 的评论。这是我的功能,以防其他人需要它。
function Inserts() {
//get the html
var h = $("#a").clone();
//now turn it into a jquery object
var jqObj = $(h);
//now parse it, let's make some modifications
var someID = "0";
$("div", jqObj).each(function (idx, elem) {
if ($(this).attr("id") == undefined)
return;
$(this).attr("id", someID + "_" + $(this).attr("id"));
});
$("#target_div").append(jqObj.html());
}