jQuery에서 클릭 핸들러를 일시적으로 비활성화하는 방법은 무엇입니까?
버튼의 클릭 이벤트를 트랩하기 위해 다음과 같은 내용이 있다고 가정합니다.
$("#button_id").click(function() {
//disable click event
//do something
//re-enable click event
}
원래 클릭 처리가 끝날 때까지 버튼의 클릭 이벤트를 일시적으로 비활성화하려면 어떻게합니까? 기본적으로 버튼을 클릭하면 div가 사라지지만 사용자가 버튼을 여러 번 빠르게 클릭하면 div가 사라지기 전에 모든 클릭을 처리합니다. div가 사라지기 전에 첫 번째 클릭 만 등록되도록 버튼을 "디 바운스"하고 싶습니다.
이 게시물이 오래되었다는 것을 알았지 만 Google에서 맨 위에 나타나고 이런 종류의 솔루션이 제공되지 않았으므로 어쨌든 게시하기로 결정했습니다.
커서 이벤트를 비활성화하고 나중에 css를 통해 다시 활성화 할 수 있습니다. 모든 주요 브라우저에서 지원되며 일부 상황에서 유용 할 수 있습니다.
$("#button_id").click(function() {
$("#button_id").css("pointer-events", "none");
//do something
$("#button_id").css("pointer-events", "auto");
}
이것은 인공 상태 변수 솔루션에 대한보다 관용적 인 대안입니다.
$("#button_id").one('click', DoSomething);
function DoSomething() {
// do something.
$("#button_id").one('click', DoSomething);
}
하나 는 한 번만 실행됩니다 (다시 연결될 때까지). 자세한 정보 : http://docs.jquery.com/Events/one
$("#button_id").click(function() {
if($(this).data('dont')==1) return;
$(this).data('dont',1);
//do something
$(this).data('dont',0);
}
$ .data ()는 ID가있는 항목에 대해서만 작동합니다.
를 사용하여 처리기를 바인딩 해제 할 수 .off
있지만주의 할 점이 있습니다. 이 작업을 수행하는 경우 처리기가 이미 실행중인 동안 다시 트리거되지 않도록 방지하려면 처리기 리 바인딩을 연기해야합니다.
예를 들어, 5 초 핫 슬립을 사용하여 핸들러 내에서 수행되는 동기적이고 계산 비용이 많이 드는 작업을 시뮬레이션하는 다음 코드를 고려하십시오 (예 : 과도한 DOM 조작).
<button id="foo">Click Me!</div>
<script>
function waitForFiveSeconds() {
var startTime = new Date();
while (new Date() - startTime < 5000) {}
}
$('#foo').click(function handler() {
// BAD CODE, DON'T COPY AND PASTE ME!
$('#foo').off('click');
console.log('Hello, World!');
waitForFiveSeconds();
$('#foo').click(handler);
});
</script>
작동하지 않습니다. 이 JSFiddle 에서 시도해 보면 알 수 있듯이 핸들러가 이미 실행 중일 때 버튼을 클릭하면 첫 번째 실행이 완료되면 핸들러가 두 번째로 실행됩니다. 당신이 jQuery를 사용하고 사용하지 않은 경우에도 무엇보다, 크롬과 파이어 폭스에서 적어도,이 사실이 될 것입니다 addEventListener
및 removeEventListener
추가하고 대신 핸들러를 제거 할 수 있습니다. 브라우저는 첫 번째 클릭 후 핸들러를 실행하고 핸들러를 바인딩 해제 및 리 바인딩 한 다음 두 번째 클릭 을 처리하고 실행할 클릭 핸들러가 있는지 확인합니다.
이 문제를 해결하려면을 사용하여 핸들러 리 바인딩을 연기해야합니다 setTimeout
. 그러면 첫 번째 핸들러가 실행되는 동안 발생하는 클릭이 핸들러 를 다시 연결 하기 전에 처리됩니다 .
<button id="foo">Click Me!</div>
<script>
function waitForFiveSeconds() {
var startTime = new Date();
while (new Date() - startTime < 5000) {}
}
$('#foo').click(function handler() {
$('#foo').off('click');
console.log('Hello, World!');
waitForFiveSeconds();
// Defer rebinding the handler, so that any clicks that happened while
// it was unbound get processed first.
setTimeout(function () {
$('#foo').click(handler);
}, 0);
});
</script>
이 수정 된 JSFiddle에서이 동작을 볼 수 있습니다 .
당연히 처리기에서 수행하는 작업이 이미 비동기식 인 경우에는 필요하지 않습니다. 브라우저에 대한 제어권을 이미 양보하고 처리기를 리 바인드하기 전에 모든 클릭 이벤트를 플러시하도록하기 때문입니다. 예를 들어 다음과 같은 코드는 setTimeout
호출 없이도 잘 작동합니다 .
<button id="foo">Save Stuff</div>
<script>
$('#foo').click(function handler() {
$('#foo').off('click');
$.post( "/some_api/save_stuff", function() {
$('#foo').click(handler);
});
});
</script>
내가 룩을 사용하여 말하기 전에 다른 사람들처럼 할 수 있습니다.
A.) 버튼 요소의 .data를 사용하여 look 변수 (또는 전역 변수) 공유
if ($('#buttonId').data('locked') == 1)
return
$('#buttonId').data('locked') = 1;
// Do your thing
$('#buttonId').data('locked') = 0;
B.) 마우스 신호 비활성화
$("#buttonId").css("pointer-events", "none");
// Do your thing
$("#buttonId").css("pointer-events", "auto");
C.) HTML 버튼 인 경우 비활성화 할 수 있습니다 (입력 [type = submit] 또는 버튼)
$("#buttonId").attr("disabled", "true");
// Do your thing
$("#buttonId").attr("disabled", "false");
그러나 다른 스레드를 조심하십시오! 애니메이션 (페이드 인 또는 페이드 아웃)이 1 초가 걸리기 때문에 여러 번 실패했습니다. 예를 들어 fadeIn / fadeOut은 두 번째 매개 변수로 콜백 함수를 지원합니다. 다른 방법이 없으면 setTimeout(callback, delay)
.
인사, 토마스
#button_id가 제출 버튼과 같은 표준 HTML 버튼을 의미하는 경우 'disabled'속성을 사용하여 버튼을 브라우저에서 비활성화 할 수 있습니다.
$("#button_id").click(function() {
$('#button_id').attr('disabled', 'true');
//do something
$('#button_id').removeAttr('disabled');
});
그러나주의해야 할 것은 이러한 일이 발생할 수있는 순서입니다. jquery hide 명령을 사용하는 경우 "$ ( '# button_id'). removeAttr ( 'disabled');"를 포함 할 수 있습니다. 콜백의 일부로, 숨기기가 완료 될 때까지 발생하지 않습니다.
콜백을 사용하는 함수의 예 :
$("#button_id").click(function() {
$('#button_id').attr('disabled', 'true');
$('#myDiv').hide(function() { $('#button_id').removeAttr('disabled'); });
});
활용 해보세요 .one()
var button = $("#button"),
result = $("#result"),
buttonHandler = function buttonHandler(e) {
result.html("processing...");
$(this).fadeOut(1000, function() {
// do stuff
setTimeout(function() {
// reset `click` event at `button`
button.fadeIn({
duration: 500,
start: function() {
result.html("done at " + $.now());
}
}).one("click", buttonHandler);
}, 5000)
})
};
button.one("click", buttonHandler);
#button {
width: 50px;
height: 50px;
background: olive;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<div id="result"></div>
<div id="button">click</div>
it is better that use current event and dont save handler in global handler. i get current element event then unbind then bind again. for a handler.
var element = $("#elemid")[0];
var tempHandler = jQuery._data(element)["events"]["click"][0].handler;
$("#elemid").unbind("click");
// do the job that click not suppose to listen;
$("#elemid").bind("click" , tempHandler );
for all handler
var element = $("#elemid")[0];
var clickHandlerList = jQuery._data(element)["events"]["click"];
var handlerList = [];
for(var i = 0 ; i < clickHandlerList .length ; i++) {
handlerList .push(clickHandlerList [i].handler);
}
$("#elemid").unbind("click");
// do the job that click not suppose to listen;
for(var i = 0 ; i < handlerList.length ; i++) {
// return back all handler to element.
$("#elemid").bind("click" , handlerList[i]);
}
I just barely ran into this problem when trying to display a loading spinner while I waited for a function to complete. Because I was appending the spinner into the HTML, the spinner would be duplicated each time the button was clicked, if you're not against defining a variable on the global scale, then this worked well for me.
var hasCardButtonBeenClicked = '';
$(".js-mela-card-button").on("click", function(){
if(!hasCardButtonBeenClicked){
hasCardButtonBeenClicked = true;
$(this).append('<i class="fa fa-circle-o-notch fa-spin" style="margin-left: 3px; font-size: 15px;" aria-hidden="true"></i>');
}
});
Notice, all I'm doing is declaring a variable, and as long as its value is null, the actions following the click will occur and then subsequently set the variables value to "true" (it could be any value, as long as it's not empty), further disabling the button until the browser is refreshed or the variable is set to null.
Looking back it probably would have made more sense to just set the hasCardButtonBeenClicked variable to "false" to begin with, and then alternate between "true" and "false" as needed.
This example work.
HTML code:
<div class="wrapper">
<div class="mask">Something</div>
</div>
jQuery:
var fade = function(){
$(".mask").fadeToggle(500,function(){
$(this).parent().on("click",function(){
$(this).off("click");
fade();
});
});
};
$(".wrapper").on("click",function(){
$(this).off("click");
fade();
});
$("#button_id").click(function() {
$('#button_id').attr('disabled', 'true');
$('#myDiv').hide(function() { $('#button_id').removeAttr('disabled'); });
});
Don't use .attr()
to do the disabled, use .prop()
, it's better.
This code will display loading on the button label, and set button to disable state, then after processing, re-enable and return back the original button text:
$(function () {
$(".btn-Loading").each(function (idx, elm) {
$(elm).click(function () {
//do processing
if ($(".input-validation-error").length > 0)
return;
$(this).attr("label", $(this).text()).text("loading ....");
$(this).delay(1000).animate({ disabled: true }, 1000, function () {
//original event call
$.when($(elm).delay(1000).one("click")).done(function () {
$(this).animate({ disabled: false }, 1000, function () {
$(this).text($(this).attr("label"));
})
});
//processing finalized
});
});
});
// and fire it after definition
}
);
참고URL : https://stackoverflow.com/questions/1263042/how-to-temporarily-disable-a-click-handler-in-jquery
'IT TIP' 카테고리의 다른 글
Android 5.0 : 최근 앱 제목 색상을 변경하는 방법은 무엇입니까? (0) | 2020.11.21 |
---|---|
Java 8에서 findAny ()와 findFirst ()의 차이점 (0) | 2020.11.21 |
Firebug에서 프로그래밍 방식으로 JavaScript 실행 중지 (0) | 2020.11.21 |
JAX-RS 리소스에서 ServletContext 가져 오기 (0) | 2020.11.21 |
HTML의 한 줄 주석 (0) | 2020.11.21 |