2010-12-28 3 views
3

두 번 이상 클릭 한 후 alert("hello") 함수가 생성되지 않는 이유를 이해하는 것이 놀랍습니다 ...이 함수를 실행하는 방법이 있습니까?jQuery html() 후 ID 선택기 사용 방법

html()을 사용하여 업데이트 한 후에는 "누르십시오"라는 id가 필요합니다.

아이디어가 있으십니까? 참조 : http://jsbin.com/atuqu3

자바 스크립트 :

$(document).ready(function(){ 
     $("#press").click(function() { 
      $("#relation-states").html('<select id="state" name="state"> <option value="Texas">Texas</option> </select><button id="press" type="button" title="" aria-haspopup="true" style="width: 175px;"><span>Select an item</span></button>');; 
      alert("hello"); 
     }); 
    }); 

HTML :

<div id="relation-states"> 
    <select id="state" name="state"> 
    <option value="New York">New York</option> 
    </select> 
    <button id="press" type="button" title="" aria-haspopup="true" style="width: 175px;"><span>Select an item</span></button> 
    </div> 

답변

5

또한 이벤트 핸들러를 제거하고 ID가 "관계-상태"로 전체 div의 내용을 대체하고 (부착 된 핸들러가있는 DOM 노드가 제거되기 때문에). 당신은 지금 또는 미래의 선택을 만족하는 모든 요소에 이벤트 처리기를 바인딩 할 경우, live 체크 아웃 :

$("#press").live("click", function() { 
     $("#relation-states").html('<select id="state" name="state"> <option value="Texas">Texas</option> </select><button id="press" type="button" title="" aria-haspopup="true" style="width: 175px;"><span>Select an item</span></button>');; 
     alert("hello"); 
    }); 

또는 delegate을 :

$("#relation-states").delegate("#press", "click", function() { 
      $("#relation-states").html('<select id="state" name="state"> <option value="Texas">Texas</option> </select><button id="press" type="button" title="" aria-haspopup="true" style="width: 175px;"><span>Select an item</span></button>');; 
      alert("hello"); 
} 
2

.html()를 사용하면 삭제 된 모든 그 요소의 자식들을 새로운 요소로 교체하십시오. 즉, 해당 자식에 연결된 모든 이벤트 처리기가 손실됩니다. 당신은 당신이 정말로 필요로하는 것을 대체하여 피할 수 있습니다 :

$('#state').html('<option value="Texas">Texas</option>'); 
+0

감사합니다. 처음에는 한 번 더 클릭 한 후 "alert()"기능을 사용하려고했습니다 ... 내 어려움은 이것이었습니다. – Vegetus