2009-01-06 5 views
50

나는 그 안에 포함 된 정렬되지 않은 목록의 큰 컬렉션을 가진 HTML 요소를 가지고 있습니다. 다른 스타일을 추가 한 페이지의 다른 곳에 배치하려면이 요소를 복제해야합니다 (jQuery를 사용하면 충분히 간단합니다).jQuery 복제본 중복 ID

$("#MainConfig").clone(false).appendTo($("#smallConfig")); 

그러나 문제는 모든 목록과 관련 목록 항목 ID를 가지고 clone 그들을 중복 것입니다. 추가하기 전에 jQuery를 사용하여 이러한 모든 중복 ID를 쉽게 대체 할 수 있습니까?

+4

@ 아담 네 일러 존재 매끈한가 도움이되지 않습니다 최선의 방법이라고 생각이 같은 문이 그렇게 할 경우

다른를 추가합니다. –

답변

38

복제 한 후에 목록 항목을 참조 할 방법이 필요한 경우 ID가 아닌 클래스를 사용해야합니다. 모든 ID = "..."을 class = "..."로 변경하십시오.

기존 코드를 다루고 있으며 ID를 클래스로 변경할 수없는 경우 추가하기 전에 id 속성을 제거해야합니다.

$("#MainConfig").clone(false).find("*").removeAttr("id").appendTo($("#smallConfig")); 

더 이상 개별 항목을 참조 할 수있는 방법이 없습니다.

+1

비슷한 것을 얻을 수 없지만 id를 대체 할 수 있습니까? – Sheff

+1

그런 다음 ID가 어떻게 변경되었는지 (예 : 접두어, 접미사) 추적하고 복제 된 요소를 참조 할 때 올바른 ID를 재구성하기 위해 문자열 연결을 사용해야합니다. 성가신. 그냥 수업을 사용하십시오. –

+0

복제 및 변경 ID : "http://stackoverflow.com/questions/10126395/how-to-jquery-clone-and-change-id" –

14
$("#MainConfig") 
    .clone(false) 
    .find("ul,li") 
    .removeAttr("id") 
    .appendTo($("#smallConfig")); 

크기를 사용해보십시오. :)

[편집] redsquare 님의 의견이 수정되었습니다.

+0

아이디를 제거하기 전에 아이디를 제거해야합니다. 그렇지 않으면 아이디가 돔에 복제됩니다. 더러운 효과가있을 수 있습니다. – redsquare

+0

솔트가 쓴 예에서 본질적으로 뭘하는지. 나는 그것을 줄 것이다. 그러나 마크 업 변경과 부모 내의 다른 요소가 속는 경우에 대비하여 모든 아이들을위한 글로벌 검색을 사용한다. – Sheff

+0

문제 없음. 내 실수 잡기 주셔서 감사합니다.] – Salty

0

페이지에 비슷한 항목이 여러 개있을 경우 ID가 아닌 클래스를 사용하는 것이 가장 좋습니다. 그렇게하면 다른 컨테이너 ID 안에 스타일을 적용 할 수 있습니다.

5

$ ("# details"). clone(). attr ('id', 'details_clone'). 이후 ("h1").

+3

아, 그게 더 짧습니다 :'var i = $ ('itemBase') ; addClass ('item'). insertAfter (i);'i.clone (true) .attr ('id', 'item'+ nextItemId ++) .removeClass ('숨김'). – dlamblin

18

OP는 중복 ID를 추가하기 전에 모든 ID를 바꾸는 방법을 요구 했으므로 이와 같은 방법이 사용될 수 있습니다.

<div id="smallConfig"> 
    <div id="MainConfig_1"> 
     <ul> 
      <li id="red_1">red</li> 
      <li id="blue_1">blue</li> 
     </ul> 
    </div> 
</div> 

코드는 다음과 같이 될 수 복제 된 블록의 모든 자식 요소 (후손)를 찾기 위해, 그리고 자신의 ID의은을 사용하여 수정 : 당신이 이와 같은 HTML 블록에 MainConfig_1를 복제하고 싶었 가정 카운터 :

var cur_num = 1; // Counter used previously. 
//... 
var cloned = $("#MainConfig_" + cur_num).clone(true, true).get(0); 
++cur_num; 
cloned.id = "MainConfig_" + cur_num;     // Change the div itself. 
$(cloned).find("*").each(function(index, element) { // And all inner elements. 
    if(element.id) 
    { 
     var matches = element.id.match(/(.+)_\d+/); 
     if(matches && matches.length >= 2)   // Captures start at [1]. 
      element.id = matches[1] + "_" + cur_num; 
    } 
}); 
$(cloned).appendTo($("#smallConfig")); 

이 같은 새로운 HTML을 만들려면 :이 러셀의 대답을 기반으로

<div id="smallConfig"> 
    <div id="MainConfig_1"> 
     <ul> 
      <li id="red_1">red</li> 
      <li id="blue_1">blue</li> 
     </ul> 
    </div> 
    <div id="MainConfig_2"> 
     <ul> 
      <li id="red_2">red</li> 
      <li id="blue_2">blue</li> 
     </ul> 
    </div> 
</div> 
3

하지만 조금 더 미적 형태의 기능. jQuery를 :

$(document).ready(function(){ 
    var cur_num = 1; // Counter 

    $('#btnClone').click(function(){ 

      var whatToClone = $("#MainConfig"); 
      var whereToPutIt = $("#smallConfig"); 

      var cloned = whatToClone.clone(true, true).get(0); 
      ++cur_num; 
      cloned.id = whatToClone.attr('id') + "_" + cur_num;     // Change the div itself. 

     $(cloned).find("*").each(function(index, element) { // And all inner elements. 
      if(element.id) 
      { 
       var matches = element.id.match(/(.+)_\d+/); 
       if(matches && matches.length >= 2)   // Captures start at [1]. 
        element.id = matches[1] + "_" + cur_num; 
      } 
      if(element.name) 
      { 
       var matches = element.name.match(/(.+)_\d+/); 
       if(matches && matches.length >= 2)   // Captures start at [1]. 
        element.name = matches[1] + "_" + cur_num; 
      } 

     }); 

     $(cloned).appendTo(whereToPutIt); 

    }); 
}); 

마크 업이 :

<div id="smallConfig"> 
    <div id="MainConfig"> 
     <ul> 
      <li id="red_1">red</li> 
      <li id="blue_1">blue</li> 
     </ul> 
     <input id="purple" type="text" value="I'm a text box" name="textboxIsaid_1" /> 
    </div> 
</div> 
2

FWIW, 내가 다리오의 기능을 사용하지만,뿐만 아니라 형태로 라벨을 잡을 필요가 있었다.

if(element.htmlFor){ 
var matches = element.htmlFor.match(/(.+)_\d+/); 
if(matches && matches.length >= 2)   // Captures start at [1]. 
    element.htmlFor = matches[1] + "_" + cur_num; 
} 
0

을 나는이

var $clone = $("#MainConfig").clone(false); 
$clone.removeAttr('id'); // remove id="MainConfig" 
$clone.find('[id]').removeAttr('id'); // remove all other id attributes 
$clone.appendTo($("#smallConfig")); // add to DOM.