2017-02-16 1 views
3

버튼의 식별자를 변경하는 클릭 이벤트가 생성되었습니다. 같은 버튼으로 두 번째 클릭 이벤트를 만들었지 만 이번에는 새 ID로 만듭니다. 버튼을 클릭하면 두 번째로 나는 항상 이드와 함께 첫 번째 행동을한다. 이 예제를 더 잘 설명하는 코드는 다음과 같습니다. 아이디어는 같은 버튼과 두 개의 서로 다른 행동을하는 것입니다 당신이 식별자를 변경하는 경우 동적으로 다음 위임 된 이벤트 핸들러를 사용해야합니다동일한 버튼으로 두 가지 다른 비헤이비어를 구현하는 방법

$('#button').on('click',function() { 
    $(this).attr('id','buttonBis'); 
}); 

$('#buttonBis').on('click',function() { 
    alert('here'); 
}); 
+0

2 ID를 새로운 버튼 번호 이벤트를 할당하고 그 colne하여 DOM 노드를 대체함으로써 이벤트 (중복을 방지) 첨부 삭제 기능을 만들기? – guradio

+0

@Rory McCrossan처럼 말했습니다. 나는 수업을 변경하고 수업 시간은 변경하지 않는다. – KubiRoazhon

답변

6

:

$(document).on('click', '#button', function() { 
 
    $(this).attr('id', 'buttonBis'); 
 
}); 
 

 
$(document).on('click', '#buttonBis', function() { 
 
    alert('here'); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 

 
<button id="button">Click me twice to see the alert()</button>

id 속성을 동적으로 변경하는 것은 좋은 생각으로 간주되지 않으므로 가능한 경우 피해야합니다. 클래스 추가/제거가 훨씬 더 나은 대안이 될 것입니다.

+0

다른 것보다 훨씬 좋습니다. +1 –

+0

네, 맞습니다. id가 항목을 고유하게 만들니까. 몇 가지 수업을 추가하여 변경하겠습니다. 감사합니다 – KubiRoazhon

0

1 개 버튼,

$('#button').on('click',function() { 
 
    $(this).attr('id','buttonBis'); 
 
    //clone the node then reissign to the same node 
 
    // which removes the previous attached events 
 
    var self = this.cloneNode(true); 
 
    $(this).replaceWith(self); 
 
    newevent(); 
 
}); 
 

 

 
var newevent = function() { 
 
\t $('#buttonBis').on('click',function() { 
 
     alert('here'); 
 
    }); 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<button id="button" >Click Me twice </button>

+1

그냥'this.parentNode.replaceChild ... 대신'FYI 대신 사용할 수있는'replaceWith()'메소드가 있습니다. –

+0

@RoryMcCrossan yep, 정말 고마워. –

관련 문제