추가 메소드 후 Jquery 클릭 이벤트가 작동하지 않음


82

그래서 테이블에 새 행을 추가하는이 버튼이 있지만 내 문제는 .new_participant_form추가 메서드가 발생한 후 더 이상 클릭 이벤트를 수신하지 않는다는 것입니다.

http://jsfiddle.net/cTEFG/

새 항목 추가를 클릭 한 다음 양식 이름을 클릭하십시오.

$('#add_new_participant').click(function() {


    var first_name = $('#f_name_participant').val();
    var last_name = $('#l_name_participant').val();
    var role = $('#new_participant_role option:selected').text();
    var email = $('#email_participant').val();


    $('#registered_participants').append('<tr><td><a href="#" class="new_participant_form">Participant Registration</a></td><td>'+first_name+ ' '+last_name+'</td><td>'+role+'</td><td>0% done</td></tr>');

    });

    $('.new_participant_form').click(function() {

        var $td = $(this).closest('tr').children('td');

        var part_name = $td.eq(1).text();
        alert(part_name);

    });
});

HTML

<table id="registered_participants" class="tablesorter">

<thead>
<tr> 
<th>Form</th>
<th>Name</th>
<th>Role</th>
<th>Progress </th>


</tr> 
</thead>


<tbody>
<tr> 
<td><a href="#" class="new_participant_form">Participant Registration</a></td>
<td>Smith Johnson</td>
<td>Parent</td>
<td>60% done</td>


</tr> 
</tbody>

</table>

<button id="add_new_participant"></span>Add New Entry</button> 

문제는 이벤트 new_participant_form가 이미 문서에있는 요소 에만 첨부 된다는 것입니다. 나중에 추가 할 요소에 대해서도 작동하도록하려면 dystroy에서 보여준 것처럼 이벤트 위임을 사용하거나 삽입하기 전에 각 앵커에 핸들러를 첨부 할 수 있습니다 (전자가 더 효율적입니다).
Asad Saeeduddin 2013 년

답변:


207

사용 :

$('#registered_participants').on('click', '.new_participant_form', function() {

이벤트 핸들러를 바인딩 한 후 추가 된 경우에도 클릭이 #registered_participants클래스가있는 모든 요소에 위임되도록 new_participant_form합니다.


4
사용하면 성능상의 단점이 $(document).on('click', '.new_participant_form', function() {});있습니까?
basZero

3
@basZero jQuery가 모든 클릭을 처리해야하므로이 #registered_participants속도가 너무 작아서 관련성이 없습니다. 더 깨끗하기 때문에 올바른 요소를 타겟팅하는 것이 가장 좋습니다.
Denys Séguret

34

.on()메서드 는 동적으로 추가되거나 이미 DOM에있는 요소에 이벤트를 위임하는 데 사용됩니다.

// STATIC-PARENT              on  EVENT    DYNAMIC-CHILD
$('#registered_participants').on('click', '.new_participant_form', function() {

  var $td = $(this).closest('tr').find('td');
  var part_name = $td.eq(1).text();
  console.log( part_name );

});


$('#add_new_participant').click(function() {

  var first_name = $.trim( $('#f_name_participant').val() );
  var last_name  = $.trim( $('#l_name_participant').val() );
  var role       = $('#new_participant_role').val();
  var email      = $('#email_participant').val();
  
  if(!first_name && !last_name) return;

  $('#registered_participants').append('<tr><td><a href="#" class="new_participant_form">Participant Registration</a></td><td>' + first_name + ' ' + last_name + '</td><td>' + role + '</td><td>0% done</td></tr>');

});
<table id="registered_participants" class="tablesorter">
  <thead>
    <tr>
      <th>Form</th>
      <th>Name</th>
      <th>Role</th>
      <th>Progress </th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td><a href="#" class="new_participant_form">Participant Registration</a></td>
      <td>Smith Johnson</td>
      <td>Parent</td>
      <td>60% done</td>
    </tr>
  </tbody>
</table>

<input type="text" id="f_name_participant" placeholder="Name">
<input type="text" id="l_name_participant" placeholder="Surname">
<select id="new_participant_role">
  <option>Parent</option>
  <option>Child</option>
</select>
<button id="add_new_participant">Add New Entry</button>

<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

자세히보기 : http://api.jquery.com/on/


10

이 문제는 .onjQuery 1.7+ 버전에서 언급했듯이 해결할 수 있습니다 .

불행히도 이것은 내 코드 내에서 작동하지 않았으므로 (1.11이 있습니다) 다음을 사용했습니다.

$('body').delegate('.logout-link','click',function() {

http://api.jquery.com/delegate/

jQuery 3.0부터 .delegate ()는 더 이상 사용되지 않습니다. jQuery 1.7 이후로 .on () 메서드로 대체되었으므로 이미 사용하지 않는 것이 좋습니다. 그러나 이전 버전의 경우 이벤트 위임을 사용하는 가장 효과적인 방법으로 남아 있습니다. 이벤트 바인딩 및 위임에 대한 자세한 내용은 .on () 메서드에 있습니다. 일반적으로 다음은 두 가지 방법에 해당하는 템플릿입니다.

// jQuery 1.4.3+
$( elements ).delegate( selector, events, data, handler );
// jQuery 1.7+
$( elements ).on( events, selector, data, handler );

이 의견은 다른 사람들에게 도움이 될 수 있습니다. :)!


1

이 시도

jQuery 버전 1.7 이상부터 on () 메서드는 bind (), live () 및 delegate () 메서드를 대체합니다.

그래서 이것을 추가하십시오,

$(document).on("click", "a.new_participant_form" , function() {
      console.log('clicked');
});

또는 자세한 내용은 여기에서 확인하십시오.


0

** 문제 해결 ** 여기에 이미지 설명 입력 // 본문에서 위임을 사용하도록 delegate () 메서드로 변경

$("body").delegate("#boundOnPageLoaded", "click", function(){
   alert("Delegated Button Clicked")
});

delegate () 메서드는 버전 3.0에서 더 이상 사용되지 않습니다. 따라서 대신 on () 메서드를 사용하십시오.
Manoj
당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.