jquery 관련 질문...
본문
중분류밑에 파란색 '추가' 버튼을 이용해 중분류명을 추가시켰습니다.
근데 문제는 리조트1,2,3,4, 으로 적혀있는 요소들은 삭제 기능이 제대로 먹는데
새로 추가된 요소에 한하여 삭제 기능이 먹히지 않습니다. ㅠㅠ 도와주세요.ㅠ
$('.division-add-btn').click(function(){
var divisionItem = $("<li class='division-item'><input type='text' class='division-ipt' placeholder='중분류명입력'><button type='button' class='gray-btn division-remove-btn'>삭제</button></li>");
$('.division-box').append(divisionItem);
});
$('.division-remove-btn').click(function(){
$(this).parent().remove();
});
!-->
답변 1
$(document).on('click', '.division-remove-btn', function(){
$(this).parent().remove();
});
원하는대로 작동하지 않는다면 아래 메뉴얼을 참고해보세요.
새로 추가되는 엘리먼트를 어떻게 컨트롤하는지에 대한 설명으로 생각됩니다.
Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time. By picking an element that is guaranteed to be present at the time the delegated event handler is attached, you can use delegated events to avoid the need to frequently attach and remove event handlers. This element could be the container element of a view in a Model-View-Controller design, for example, or document if the event handler wants to monitor all bubbling events in the document. The document element is available in the head of the document before loading any other HTML, so it is safe to attach events there without waiting for the document to be ready.
In addition to their ability to handle events on descendant elements not yet created, another advantage of delegated events is their potential for much lower overhead when many elements must be monitored. On a data table with 1,000 rows in its tbody, this example attaches a handler to 1,000 elements:
$( "#dataTable tbody tr" ).on( "click", function() {
console.log( $( this ).text() );
});
An event-delegation approach attaches an event handler to only one element, the tbody, and the event only needs to bubble up one level (from the clicked tr to tbody):
$( "#dataTable tbody" ).on( "click", "tr", function() {
console.log( $( this ).text() );
});