programing

jQuery - 이벤트가 시작된 후 온클릭 이벤트 청취자를 일시적으로 비활성화하려면 어떻게 해야 합니까?

codeshow 2023. 4. 2. 11:43
반응형

jQuery - 이벤트가 시작된 후 온클릭 이벤트 청취자를 일시적으로 비활성화하려면 어떻게 해야 합니까?

이벤트가 실행된 후 온클릭 이벤트청취자(jQuery 우선)를 일시적으로 비활성화하려면 어떻게 해야 합니까?

예:

사용자가 버튼을 클릭하여 아래 기능을 실행한 후 클릭 리스너를 비활성화하여 django 뷰와 동일한 명령을 실행하지 않도록 합니다.

$(".btnRemove").click(function(){
   $(this).attr("src", "/url/to/ajax-loader.gif");
   $.ajax({
        type: "GET",
        url: "/url/to/django/view/to/remove/item/" + this.id,
        dataType: "json",
        success: function(returned_data){
            $.each(returned_data, function(i, item){
              // do stuff                       
     });
   }
});

정말 감사해요.

알도

여러 가지 방법이 있어요.예를 들어 다음과 같습니다.

$(".btnRemove").click(function() {
    var $this = $(this);
    if ($this.data("executing")) return;
    $this
        .data("executing", true)
        .attr("src", "/url/to/ajax-loader.gif");
    $.get("/url/to/django/view/to/remove/item/" + this.id, function(returnedData) {
        // ... do your stuff ...
        $this.removeData("executing");
    });
});

또는

$(".btnRemove").click(handler);

function handler() {
    var $this = $(this)
        .off("click", handler)
        .attr("src", "/url/to/ajax-loader.gif");
    $.get("/url/to/django/view/to/remove/item/" + this.id, function(returnedData) {
        // ... do your stuff ...
        $this.click(handler);
    });
}

또한 이벤트 위임을 사용하여 코드를 명확하게 하고 성능을 향상시킬 수 있습니다.

$(document).on("click", ".btnRemove:not(.unclickable)", function() {
    var $this = $(this)
        .addClass("unclickable")
        .attr("src", "/url/to/ajax-loader.gif");
    $.get("/url/to/django/view/to/remove/item/" + this.id, function(returnedData) {
        // ... do your stuff ...
        $this.removeClass("unclickable");
    });
});

를 다시 없는 는, 을할 수 ..one()방법.1회만 실행되는 핸들러를 바인드합니다.jQuery 문서 참조:http://api.jquery.com/one

클릭 이벤트 수신기를 비활성화할 기간입니다. 방법은를 바인드 입니다.unbind http://docs.jquery.com/Events/unbind 를 참조해 주세요.

그러나 이벤트를 바인딩 해제하지 않고 나중에 다시 바인딩하는 것이 가장 좋습니다.대신 부울을 사용합니다.

var active = true;
$(".btnRemove").click(function() {
    if (!active) {
        return;
    }
    active = false;
    $(this).attr("src", "/url/to/ajax-loader.gif");
    $.ajax({
        type: "GET",
        url: "/url/to/django/view/to/remove/item/" + this.id,
        dataType: "json",
        success: function(returned_data) {
            active = true; // activate it again !
            $.each(returned_data, function(i, item) {
                // do stuff                       
            });
        }
    });
});

edit: 안전을 위해 다른 Ajax 완료 루틴에도 주의를 기울여야 합니다(다음 세 가지만 있습니다).success,error,complete 문서 참조) 또는 기타active거짓으로 남을 수도 있어요

왜 버튼을 해제하지 않는가?이 리스트너만을 무효로 하고 싶은 특별한 이유가 있습니까?BTB, 당신의 코드로 볼 때, 당신이 Ajax 콜을 하고 있는 것을 알 수 있습니다.즉, 콜이 돌아올 때까지 사용자를 차단하고 싶은 것입니까?만약 그렇다면 차단해 볼 수 있습니다.UI, jQuery 플러그인

AJAX 요청을 추적하기 위해 글로벌 변수를 설정합니다.

var myApp = {
  ajax: null
}

그리고 이 작은 마법으로 동시 요청을 멈출 수 있는...

// Fired when an AJAX request begins
$.ajaxStart(function() { myApp.ajax = 1 });

// Fired when an AJAX request completes
$.ajaxComplete(function() { myApp.ajax = null });

// Fired before an AJAX request begins
$.ajaxSend(function(e, xhr, opt) {
  if(myApp.ajax != null) {
    alert("A request is currently processing. Please wait.");
    xhr.abort();
  }
});

이 어프로치에서는, 코드를 재검토해, AJAX 콜을 모두 변경할 필요는 없습니다.('부속' 솔루션이라고 하는 것)

부울 값을 기준으로 클릭 내에서 액션을 수행할 수 있습니다.클릭하면 부울값과 uset set Timeout()을 변경하여 몇 초 후에 다시 변경합니다.그러면 사용자가 버튼을 몇 초마다 한 번만 클릭할 수 있습니다.

var isEnabled = true;

$("a.clickMe").click(function(e){
  e.preventDefault();
  if (isEnabled == true) {
    isEnabled = false; // disable future clicks for now
    do_Something();
    setTimeout(function(){
      isEnabled = true;
    }, 3000); // restore functionality after 3 seconds
  }
});

나는 'ajax-running'과 같은 수업을 사용할 것이다.클릭 이벤트는 클릭된 요소에 'ajax-running' 클래스가 없는 경우에만 실행됩니다.콜을 에이잭스 하는 즉시 다시 클릭할 수 있도록 'ajax-running' 클래스를 삭제할 수 있습니다.

$(".btnRemove").click(function(){
    var $button         = $(this);
    var is_ajaxRunning  = $button.hasClass('ajax-running');
    if( !is_ajaxRunning ){
        $.ajax({
            ...
            success: function(returned_data) {
                ...
                $button.removeClass('ajax-running');
            });
        };
    }   
});

버튼을 비활성화한 다음 Ajax 완료 루틴에서 다시 활성화하는 것이 좋습니다(성공 또는 실패, 기억하십시오).브라우저가 버튼을 비활성화하는 것을 인식하지 못할 경우 버튼에 자신의 플래그를 붙여 되돌릴 수 있습니다(예를 들어 다음과 같은 속성을 설정합니다).data-disabled, 를 사용합니다.data-prefix는 HTML5와 호환성이 있습니다.그러나 실제로 브라우저가 버튼을 비활성화하지 않는 문제가 발생하지 않는 한 이 정도면 충분하다고 생각합니다.

var ajaxAction = function() {
    var ele = $(this);
    ele.unbind("click", ajaxAction);
    ele.attr("src", "/url/to/ajax-loader.gif");
    $.ajax({
        type: "GET",
        url: "/url/to/django/view/to/remove/item/" + this.id,
        dataType: "json",
        success: function(returned_data) {
            $.each(returned_data, function(i, item) {
            });
        },
        complete: function() {
            ele.bind("click", ajaxAction);
        }
    });
}
$(".btnRemove").click(ajaxAction);

Ajax를 통해 게시하는 경우 클릭 시 버튼을 비활성화하고 프로세스가 완료된 후 활성화할 수 있습니다.그러나 회신할 경우 버튼을 비활성화할 수 없습니다.버튼을 무효로 하면, 서버측의 클릭 이벤트가 발생하지 않습니다.클릭할 때 버튼을 숨기고 사용자에게 친숙한 메시지를 표시하세요.포스트백의 asp.net 버튼을 비활성화하는 방법에 대한 게시물이 도움이 됩니다.

버튼(또는 div 포함)을 숨길 수도 있습니다.

$(".btnRemove").click(function() {
   $(this).hide();
   // your code here...
})

다시 표시해야 할 경우 .show()를 호출할 수 있습니다.

또한 사용 사례에 따라 로드 오버레이 사용을 고려해야 합니다.

언급URL : https://stackoverflow.com/questions/1921855/jquery-how-can-i-temporarily-disable-the-onclick-event-listener-after-the-even

반응형