2012-01-13 4 views
0

나는 다음과 같은 HTML이 -반복적으로 스캔 DOM 요소 - 자바 스크립트

<a> 
    <b> 
    .... 

    ..... 
    <input type="button" name="add" onclick="..." value="add another"/> 
    </d> 
    </b> 
.... 
</a> 

을 그리고 난 다음 JS 내가 형 버튼의 입력을 추가 할 지금

/** 
* Dynamically add a remove button on next to the add button. 
* 
*/ 
addRemoveButton = function(node) { 
    if(node.nodeType == 3) { 
     if(node.nodeName == "input") { 
      if(node.getAttribute("type") == "button") { 
       if(node.getAttribute("name") == "add") { 
        var removeButton = node.cloneNode(true); 
        removeButton.removeAttribute("name"); 
        removeButton.setAttribute("value", "remove"); 
        removeButton.setAttribute("onclick", ""); 
        removeButton.setAttribute("id", ""); 
        (node.parentNode).appendChild(removeButton); 
        return; 
       } 
      } 
     } 
    } 
    if(node.nodeType == 1) { 
     var list = node.childNodes; 
     var i = 0; 
     while(i<list.length) { 
      return addRemoveButton(list[i]); 
      i++; 
     } 
    } 
    return; 
} 

을 snippets- 사용 (제거 버튼) 위의 목록에 표시된 현재 버튼 옆에 있습니다. 나는 이것을 재귀 적으로 시도했다. 그러나 이것은 효과가 없습니다. 위의 코드에서 문제를 찾을 수 있습니까?

답변

1

내가 알 수있는 한, 당신의 코드는 꽤 멀리 떨어져있었습니다. 잘못된 nodeType을 사용하고 nodeName에 잘못된 대소 문자가 포함되어 있으며 방대한 중첩 if 문에 대한 이유가 없습니다.

addRemoveButton = function(node) { 
    if (node.nodeType == 1) { 
     if (node.nodeName.toLowerCase() == "input" && 
      node.getAttribute("type") == "button" && 
      node.getAttribute("name") == "add") { 
      var removeButton = node.cloneNode(true); 
      removeButton.removeAttribute("name"); 
      removeButton.setAttribute("value", "remove"); 
      removeButton.setAttribute("onclick", ""); 
      removeButton.setAttribute("id", ""); 
      (node.parentNode).appendChild(removeButton); 
      return; 
     } else { 
      var list = node.childNodes; 
      for (var i=0; i < list.length; i++) { 
       // be aware of childNodes changing on us live here 
       // when we modify the DOM 
       addRemoveButton(list[i]); 
      } 
     } 
    } 
} 

addRemoveButton(document.body); 

당신이 여기서 일 볼 수 있습니다 : 그러나, 당신이 이런 식으로 재귀 적으로 작동 할 수 http://jsfiddle.net/jfriend00/WCj4b/

jQuery를 (당신은 또한 귀하의 질문을 태그하는) 사용 및 복제 작업을 계속 사용하면 이 작업을 수행 할 수 있습니다 여기

$("input[type='button'][name='add']").each(function(index, el) { 
    $(this).clone(false) 
     .val("remove") 
     .removeAttr("name") 
     .attr("onclick", "") 
     .attr("id", "") 
     .insertAfter(this); 
}); 

데모 : http://jsfiddle.net/jfriend00/JKsZC/

하거나 오히려 그쪽을 새 HTML을 삽입 훨씬, 훨씬 더 간단 버전 n은 기존의 버튼을 복제 : 여기

$("input[type='button'][name='add']").after('<input type="button" value="Remove" />'); 

데모 : 영업의 코드는 측면 기존 따라 새 버튼을 만들려고한다 http://jsfiddle.net/jfriend00/vSZwp/

+0

OP가 무엇을 잘못했는지 보여주는 것은 좋지만 jQuery와 같은 라이브러리를 사용하면 그런 종류의 코드를 작성할 필요가 없습니다. –

+0

모두에게 감사드립니다. – Acn

+0

@JuanMendes - 동의합니다. 그래서 jQuery 버전을 썼다. – jfriend00

1

왜 재귀 적입니까? 기존 단추를 찾으려면? jQuery가 검색에 대해 걱정할 수 있도록하십시오. 제거 버튼을 사용하여 필요한 작업을 수행하려면 Tweak this를 조정하십시오.

+0

. 코드는 기존 버튼을 변경하는 것입니다. – jfriend00

+0

@ jfriend00 아니야. http://jsfiddle.net/hhHGW/ –

+0

OP의 코드가 제대로 작동하지 않지만 cloneNode가 복제 단추를 만든 다음 해당 복제 단추를 "제거"단추로 만들려고합니다. 내 답변에서 작동 않는 OP 코드 버전을 만들었습니다. – jfriend00

관련 문제