2014-05-18 3 views
-1

버튼을 사용할 때 내 버튼에 문제가 있습니다. btndel이 작동하지 않습니다. 여기 클릭 이벤트가 작동하지 않습니다.

스크립트입니다 :

$('#btnadd').bind('click', function() { 
    var scount = $("#support-list").find('li').length; 
    var tmpStr = $('#txtaddsupportname').val(); 
    var str = “<li>"; 
    var str += “<img src='../wp-content/plugins/hamaJob/admin/assets/image/arrow.png' width='16' height='16' class='handle'/>"; 

    str += "<strong alt="+ scount +">" + tmpStr + "</strong>"; 
    str += "<input type='button' id='btndel'/>"; 
    str += "</li>"; 

    $('#support-list').append(str); 
}); 

$('#btndel').bind('click', function(){ 
     alert(this); 
}); 

그러나,이 스크립트 작업을 수행합니다

str += "<input type='button' id='btndel' onclick='btndel(this)'/>"; 
btndel = function(e){ alert(this); } 

사람이 차이를 설명 할 수 있을까요?

+0

당신이 버튼 dynamicaly를 추가 사용? // 네 번째 줄의 큰 따옴표를 확인하십시오. – chepe263

+0

버튼을 만든 후에 사용할 수있는 click 이벤트에 바인딩해야합니다. 다른 지점, del 버튼이 여러 번 추가됩니다. "id"는 중복 될 수 없습니다. 따라서이 경우 ID에 의존하지 마십시오. –

답변

0

, 첫 번째 예제가 작동하지 않는 이유를 먹으 렴 :

는 여기에 모두 보여주는 바이올린입니다. .delegate()

확인이 업데이트 된 코드 jsfiddle

$('#btnadd').bind('click', function() { 
    var scount = $("#support-list").find('li').length; 
    var tmpStr = $('#txtaddsupportname').val(); 
    var str = "<li>"; 
    str += "<img src='../wp-content/plugins/hamaJob/admin/assets/image/arrow.png' width='16' height='16' class='handle'/>"; 

    str += "<strong alt="+ scount +">" + tmpStr + "</strong>"; 
    str += "<input type='button' id='btndel'/>"; 
    str += "</li>"; 

    $('#support-list').append(str); 
}); 
$("#support-list").delegate("#btndel", "click", function(){ 
     alert(this); 
}); 
0

클릭 이벤트를 바인딩 할 때 문제가 발생합니다. 첫 번째 예에서는 사용자가 btnadd 버튼을 클릭 할 때 btndel 요소를 만듭니다. 그래서, 때이 기능은 jQuery를이 요소에 처리기를 바인딩하는 요소가 DOM에없는

$('#btndel').bind('click', function(){ 
    alert(this); 
}); 

라고합니다.

두 번째 예제는 함수를 참조하는 요소를 만들기 때문에 작동합니다.

event delegation 중 하나를 사용하도록 업데이트하거나 요소를 만든 후에 bind을 호출하면 올바르게 작동합니다. 새로 추가 삭제 버튼이 DOM에없는 http://jsfiddle.net/Z4ajL/

0

Demo Fiddle
jQuery를

$(document).on('click','#btndel', function(){ 
     alert(this); 
}); 
관련 문제