삭제 버튼이 있습니다. 버튼을 클릭하면 두 번째 버튼을 생성하여 사용자가 실제로 뭔가를 삭제하려고하는지 확인합니다. 하지만 : 두 번째 버튼을 클릭하면 $('.deleteConfirmed').click(function() {
가 실행되지 않습니다.JQuery에서 생성 된 요소에 대한 클릭 함수
정확히 어떻게 JQuery가 작동하는지 잘 모르겠지만 두 번째 버튼이 존재하기 전에 클릭 리스너가 생성 되었기 때문에 이러한 현상이 발생한다고 생각하십니까? 이것이 사실이라면 두 번째 버튼을 클릭하기위한 해결책은 무엇입니까 deleteEntityConfirmed(id)
?
아마도 두 번째 버튼의 HTML onclick
속성을 사용하여이 작업을 수행 할 수 있지만 JQuery는이 시나리오에 대해보다 세련된 솔루션을 제공합니까?
가 여기 내 시나리오를 보여주는 몇 가지 코드, 난 오직 관련 부분을 유지하기 위해 노력
HTML :.
<button class="delete" data-id="5">
Delete
</button>
<div id="somewhere"></div>
JS : 당신은 이벤트 위임을 할 필요가
$(function() {
$('.delete').click(function() {
var id = $(this).data('id');
$('#somewhere').empty().append('<button class="deleteConfirmed" data-id="' + id + '">I\'m sure I want to delete</button>');
});
$('.deleteConfirmed').click(function() {
alert("debug message"); // we don't get here when clicking the second button. It seems to not be listening to it
var id = $(this).data('id');
deleteEntityConfirmed(id);
});
});
function deleteEntityConfirmed(id){
// If we'd get here after clicking the second button, this would be full success
alert("Deleting id " + id);
}
더 요소가 생성 읽기 동적으로, 당신은 이벤트를 위임 할 수있다. '$ (document) .on (클릭, ".deleteConfirmed", function() {...});' –
[위임 행사] (http://api.jquery.com/on/#direct-and -delegated-events) – hungerstar