2017-02-20 1 views
2

$('element').remove();이 작동하지 않는 문제가 있습니다. 문법 문제가 있고 클릭이 버튼에 올바르게 등록되지 않은 경우 많은 다른 답변을 읽었습니다.JQuery 제거가 제대로 작동하지 않습니다.

다른 문제가 있습니다. 클릭이 작동하지만 제거 된 유일한 것은 newRowDiv입니다.

그것은 <newRowDiv><child><child><child></newRowDiv> 을 시작하고 끝 <child><child><child> newRowDiv가 없어하지만 아이들이 그냥 남아 있습니다. 코드 스 니펫 (snippet)가 실행 :이 내 코드

buildRows = function(){ 
 
      //Adds the new div to the placement div 
 
      var placementDiv = $('#placementDiv'); 
 
      placementDiv.append("<div class='newRowDiv'></div>"); 
 
      //Adds the child elements to the new div 
 
      var newRowDiv = $(".newRowDiv:last"); 
 
      newRowDiv.append("<label>Title</label>"); 
 
      newRowDiv.append("<input>"); 
 
      newRowDiv.append("<a id='plusButton'>Plus</a>"); 
 

 
      //Adds the click event to the new plus button (Works fine) 
 
      newRowDiv.find('#plusButton').click(function (event) { 
 
       var button = $(event.target); 
 
       //Adds the delete button (Works fine) 
 
       var newRowDiv = button.parent('.newRowDiv'); 
 
       newRowDiv.append('<a id="deleteButton">Delete</a>'); 
 
       //Adds the click event to the button (Works fine) 
 
       newRowDiv.find('#deleteButton').click(function (event) { 
 
        //Removes the parent newRowDiv and all child elements (Doesn't work) 
 
        var button = $(event.target); 
 
        button.closest('.newRowDiv').remove(); 
 
       }); 
 

 
       //Removes the plus button (Works fine) 
 
       button.remove(); 
 

 
       //Adds the new rows section (Works fine) 
 
       buildRows(); 
 
       //Without this the new elements don't display correctly 
 
       //With this the remove only removes the element and leaves it's children behind 
 
       placementDiv.trigger('create'); 
 
      }); 
 
     } 
 
buildRows()
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div id="placementDiv"> 
 
    </div>

편집하는 일에 대해 인 trigger('create')

을 추가 할 때까지 이상한 것은 코드가 잘 작동합니다. 나는 단지 jquery 모바일 형식을 추가하는 트리거 ('생성')를 실행할 때 내 물건에 문제가 있습니다.

편집 2 : jquery 모바일의 팝업 형식과 관련이있는 것으로 보입니다. 팝업없이 코드 스 니펫에서 제대로 작동하고 트리거 ('생성')를 추가하기 전에 원래 코드에서 올바르게 작동합니다.

+1

이 함수는 행을 추가하는 데 여러 번 사용됩니까? 그렇다면 같은 ID의 버튼을 여러 개 추가하는 것입니다. HTML이 잘못되었습니다. ID는 고유해야합니다. 정의하려는 요소가 유효하지 않아 클릭 이벤트가 실행되지 않을 가능성이 큽니다. 그것을 밖으로 분류하고 아직도 문제가 있는지보십시오. 그리고 스 니펫이 컴파일되지 않습니다. 결국 괄호가 빠져 있습니까? – ADyson

+1

다른 'bind'내부에서 'bind'하면 이벤트는 부모 바인딩에서 초기 클릭을 클릭 한 후에 만 ​​바인딩됩니다. 두 번째'click()'을 처음으로 같은 레벨에서 바깥쪽으로 움직이면 작동을 시작합니다. –

+0

@Andrei 바인드가 잘 작동합니다. Chrome에서 javascript 디버거를 사용하여 확인했습니다. 클릭 이벤트가 걸렸습니다 – darthNater

답변

-2

.click() 대신 .delegate()를 사용해보십시오.

+2

http://api.jquery.com/delegate/이 메소드는 더 이상 사용되지 않습니다. 그것은 jQuery 1.7에서'.on' 방법으로 대체되었습니다. – ADyson

관련 문제