Javascript
[JS/jQuery] click 이벤트 무한반복 / 중복 발생 처리
coding-restaurant
2020. 10. 20. 17:30
728x90
728x90
JS 개발 시 클릭 click 이벤트가 무한 반복해서 들어올 때...
"클릭 이벤트를 재정의하면 (같은 엘리먼트에 중복해서 클릭 이벤트를 발생시키면)
이벤트 대체가 아닌 중복이 되어 누적된 모든 이벤트가 다 실행된다.
따라서 off()를 사용해서 중복을 방지해야한다. "
$("#id").off().on('click', function() {
//do something
}
//or
$("#id").off("click").on('click', function() {
//do something
}
//https://yunzema.tistory.com/49
생각해보면 당연한 것이지만,
"같은 element에 중복해서 클릭 이벤트를 발생시키면 그 수만큼 중복 실행된다"
마지막으로 설정한 이벤트를 제외하고 마지막에 정의된 것만 실행하려면
off를 사용해도 되지만 이벤트를 unbind한 후 bind를 해 준다.
//클릭이벤트 unbind
$("#test-button2").unbind("click");
//클릭이벤트 bind
$("#test-button2").bind("click",function(){
alert("click event");
});
// or
//클릭이벤트 unbind & bind
$("#test-button2").unbind("click").bind("click",function(){
alert("click event");
});
//https://6developer.com/3
.bind
// 사용법 요약
$("#element").bind('click', test_function);
function test_function(){
alert();
}
<button id="element">
button elem.
</button>
쉽게 말하면 jQuery 이벤트를 다른 함수로 연결(묶어주는) 함수 (by.제타위키)
728x90
728x90