2

前提:

我想从文档中取出一大块 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());

}

4

2 回答 2

2

使用clone而不是获取 html 并创建新元素。克隆后,您可以在将块重新插入所需的位置之前更改属性。

请注意,在重新插入之前更改对象的 id 是准强制性的。用来attr("id","anotherId")做。

于 2012-06-19T17:04:38.393 回答
1

clone()是要走的路,它很简单,专为此类任务而设计。

顺便说一句,你的方法的问题是,

你在做,

var h = $("#a").html();
var jqObj = $(h);

即你正在尝试这个,

var jqObj = $('<div id="aaa">...</div><div id="bbb">...</div><div id="ccc">...</div>')

但是,传递给$函数的标记字符串没有根元素,$函数需要根元素才能将标记字符串(带标签的字符串)转换为 jQuery 对象。

所以,如果你需要在你的方法中找到一个解决方案,你可以做这样的事情。

$(function(){
    var h = $("#a").wrap('<div />').parent().html();
    var jqObj = $(h);  
    $("div",jqObj).each(function (idx, elem) {
        //elem is a HTMLDivElement type
        var jq = $(this);
        console.log(jq.attr('id')); 
        // I want to access the id, class etc. of the div elements here            
    });
});
于 2012-06-19T17:36:20.407 回答