2013-01-17 76 views
0

所以我有一些HTML我想克隆几次并附加到文档中。这只是典型的HTML表单。但由于像<label for="something">这样的东西基于元素ID工作,所以如果jquery clone()'d元素中的每个HTML元素除了它们所有的克隆对象之外都可以具有唯一的ID,那就太好了。就像猜测我如何做到这一点一样,我想知道是否有可能让我的初始元素中的ID都包含一些唯一的字符串。然后,我可以以某种方式遍历元素,并用_1,_2,_3等替换该字符串。替换jquery克隆对象中的html元素的ID号

我还没有走得很远,但它看起来像这样应该工作。

$(document).ready(function(){ 
    var toReplace = "containerUniqueCharacterString1234"; 
    var copy = $('#containerUniqueCharacterString1234').clone(true); 

    copy[0].style.display = "block"; //so i can reference the first element like this 

    console.log(copy[0]); //[object HTMLDivElement] 

    $('body').append(copy); 

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

    var children = copy[index].childNodes; 
    console.log(children); //[object NodeList] 

    var len = children.length; 

    if (copy[index].childNodes.length > 0){ 
     if (copy[index].childNodes.hasOwnProperty('id')){ 

     //replace the toReplace string with an incremented number here(?) 
     //annnnd this is where i've gotten in too deep and made this overly complex 

     } 
    } 

    $('#otherResults').append(len); 

    }); 
}); 

http://jsbin.com/ecojub/1/edit

或者,也许有一个更简单得多的方式来做到这一点。 谢谢!

+0

你也可以在输入元素周围包装一个标签。里程可能会有所不同:) –

+0

在克隆中使用类不是更好吗? – Popnoodles

+0

@ popnoodles大概。但正如我所解释的,有些东西需要特定的ID。所以对我来说,这是必须的。谢谢 – 1252748

回答

1

如果您复制HTML元素多次仅用于显示,也许您应该考虑使用模板引擎而不是复制DOM元素,这些元素很昂贵且维护性较差。下划线有一个非常容易使用的功能,http://documentcloud.github.com/underscore/#template

+0

好的。 4KB。很酷。虽然我仍然对如何遍历jquery对象和改变特定属性感兴趣,但我一定会检查一下。谢谢! – 1252748

+0

你在想什么可能是一个多功能的函数,可以递归地进入某些DOM元素并修改子元素。以下是我添加到jsbin页面的示例,http://jsbin.com/ecojub/6/edit – jet