ProgramingTip

jQuery를 사용하여 두 번 클릭을 방지하는 방법은 무엇입니까?

bestdevel 2021. 1. 9. 16:28
반응형

jQuery를 사용하여 두 번 클릭을 방지하는 방법은 무엇입니까?


다음과 같은 버튼이 있습니다.

<input type="submit" id="submit" value="Save" />

jQuery 내에서 다음을 사용하고 여전히 두 번 클릭을 허용합니다.

<script type="text/javascript">

$(document).ready(function () {

    $("#submit").one('click', function (event) {  

더블 클릭을 방지 할 수있는 방법에 대한 아이디어가 있습니까?


jQuery의 one () 하나는 다음 이벤트 처리기를 제거합니다.

어떤 요구 사항을 요구 사항을 충족하지 못하는 경우 버튼을 클릭 할 수 있습니다.

$(document).ready(function () {
     $("#submit").one('click', function (event) {  
           event.preventDefault();
           //do something
           $(this).prop('disabled', true);
     });
});

ID 사용하면를 해당 요소에, 대한 참조로 함수를 submit덮어 쓰므로 문제가 발생할 수 있습니다 form.submit.


한 가지 더 해결책 :

$('a').on('click', function(e){
    var $link = $(e.target);
    e.preventDefault();
    if(!$link.data('lockedAt') || +new Date() - $link.data('lockedAt') > 300) {
        doSomething();
    }
    $link.data('lockedAt', +new Date());
});

여기에서 마지막 클릭 시간을 데이터 속성으로 저장 한 다음 이전 클릭이 0.3 초 ​​이상 전인지 확인합니다. 거짓 인 경우 (0.3 초 ​​미만) 마지막 클릭 시간 만 업데이트하고 참인 경우 작업을 수행합니다.

jsbin


대부분의 솔루션이 레이블 또는 DIV와 같은 요소 (예 : Kendo 컨트롤을 사용할 때)를 클릭하면 작동하지 않는다는 것을 발견했습니다. 그래서 저는이 방법을 만들었습니다.

function isDoubleClicked(element) {
    //if already clicked return TRUE to indicate this click is not allowed
    if (element.data("isclicked")) return true;

    //mark as clicked for 1 second
    element.data("isclicked", true);
    setTimeout(function () {
        element.removeData("isclicked");
    }, 1000);

    //return FALSE to indicate this click was allowed
    return false;
}

이벤트 시작 여부를 결정해야하는 장소에서 사용하십시오.

$('#button').on("click", function () {
    if (isDoubleClicked($(this))) return;

    ..continue...
});

내 솔루션 : https://gist.github.com/pangui/86b5e0610b53ddf28f94 더블 클릭을 방지하지만 1 초 후에 더 많은 클릭을 허용합니다. 도움이 되셨기를 바랍니다.

다음은 코드입니다.

jQuery.fn.preventDoubleClick = function() {
  $(this).on('click', function(e){
    var $el = $(this);
    if($el.data('clicked')){
      // Previously clicked, stop actions
      e.preventDefault();
      e.stopPropagation();
    }else{
      // Mark to ignore next click
      $el.data('clicked', true);
      // Unmark after 1 second
      window.setTimeout(function(){
        $el.removeData('clicked');
      }, 1000)
    }
  });
  return this;
}; 

제 경우에는 jQuery 1에 몇 가지 부작용이 결국 다음을 사용했습니다.

$(document).ready(function(){
  $("*").dblclick(function(e){
    e.preventDefault();
  });
});

매우 잘 작동하고 더 간단 해 보입니다. 위치 : http://www.jquerybyexample.net/2013/01/disable-mouse-double-click-using-javascript-or-jquery.html


이 방법을 양식에 제안면 한 번에 두 번 클릭 또는 더 많은 클릭을 처리합니다. 일단 요청을 보내면 다시 요청을 보낼 수 없습니다.

<script type="text/javascript">
    $(document).ready(function(){
            $("form").submit(function() {
                $(this).submit(function() {
                    return false;
                });
                return true;
            }); 
    }); 
</script>

그것은 확실히 당신을 도울 것입니다.


"쉬워요"

$(function() {
     $('.targetClass').dblclick(false);
});

어느 쪽이든 문제가 있습니다. setTimeout ()을 사용하여 더블 클릭을 피할 수 있습니다.

//some codes here above after the click then disable it

// 여기에서 확인하세요.

// btn 태그에있는 속성이 있다면 // 반환합니다. 그것을 js로 변환하십시오.

$('#btn1').prop("disabled", true);

setTimeout(function(){
    $('#btn1').prop("disabled", false);
}, 300);

내가 작동하는 솔루션입니다. 더블 클릭으로 클래스를 토글하지 않도록 작동합니다.

$('*').click(function(event) {
    if(!event.detail || event.detail==1){//activate on first click only to avoid hiding again on double clicks
        // Toggle classes and do functions here
        $(this).slideToggle();
    }
});

/*
Double click behaves as one single click


"It is inadvisable to bind handlers to both the click and dblclick events for the same element. The sequence of events triggered varies from browser to browser, with some receiving two click events before the dblclick and others only one. Double-click sensitivity (maximum time between clicks that is detected as a double click) can vary by operating system and browser, and is often user-configurable."

That way we have to check what is the event that is being executed at any sequence. 

   */
       var totalClicks = 1;

 $('#elementId').on('click dblclick', function (e) {

 if (e.type == "dblclick") {
    console.log("e.type1: " + e.type);
    return;
 } else if (e.type == "click") {

    if (totalClicks > 1) {
        console.log("e.type2: " + e.type);
        totalClicks = 1;
        return;
    } else {
        console.log("e.type3: " + e.type);
        ++totalClicks;
    }

    //execute the code you want to execute
}

});

이것은 내 첫 번째 게시물이며 경험이 매우 부족한 쉽게 가십시오.하지만 누군가에게 도움이 될만한 유효한 기여가 있다고 생각합니다 ...

때로는 반복 클릭 사이에 매우 큰 시간 창이 필요합니다 (예 : 이메일 앱을 여는 데 몇 초가 걸리고 다시 트리거되는 것을 원하지 않는 mailto 링크).하지만 속도를 늦추고 싶지는 않습니다. 다른 곳에서 사용자. 내 솔루션은 다른 곳에서 두 번 클릭 기능을 유지하면서 이벤트 유형에 따라 링크에 클래스 이름을 사용하는 것입니다.

var controlspeed = 0;

$(document).on('click','a',function (event) {
    eventtype = this.className;
    controlspeed ++;
    if (eventtype == "eg-class01") {
        speedlimit = 3000;
    } else if (eventtype == "eg-class02") { 
        speedlimit = 500; 
    } else { 
        speedlimit = 0; 
    } 
    setTimeout(function() {
        controlspeed = 0;
    },speedlimit);
    if (controlspeed > 1) {
        event.preventDefault();
        return;
    } else {

        (usual onclick code goes here)

    }
});

비슷한 문제가 있었지만 버튼을 비활성화해도 트릭이 완전히 수행되지 않았습니다. 버튼을 클릭했을 때 발생하는 다른 작업이 있었고 때로는 버튼이 곧 비활성화되지 않았고 사용자가 두 번 클릭했을 때 2 개의 이벤트가 발생했습니다.
나는 Pangui의 타임 아웃 아이디어를 가지고 두 기술을 결합하여 버튼을 비활성화하고 타임 아웃을 포함했습니다. 그리고 간단한 jQuery 플러그인을 만들었습니다.

var SINGLECLICK_CLICKED = 'singleClickClicked';
$.fn.singleClick = function () {
    var fncHandler; 
    var eventData;
    var fncSingleClick = function (ev) {
        var $this = $(this);
        if (($this.data(SINGLECLICK_CLICKED)) || ($this.prop('disabled'))) {
            ev.preventDefault();
            ev.stopPropagation();
        }
        else {
            $this.data(SINGLECLICK_CLICKED, true);
            window.setTimeout(function () {
                $this.removeData(SINGLECLICK_CLICKED);
            }, 1500);
            if ($.isFunction(fncHandler)) {
                fncHandler.apply(this, arguments);
            }
        }
    }

    switch (arguments.length) {
        case 0:
            return this.click();
        case 1:
            fncHandler = arguments[0];
            this.click(fncSingleClick);
            break;
        case 2: 
            eventData = arguments[0];
            fncHandler = arguments[1];
            this.click(eventData, fncSingleClick);
            break;
    }
    return this;
}

그리고 다음과 같이 사용하십시오.

$("#button1").singleClick(function () {
   $(this).prop('disabled', true);
   //...
   $(this).prop('disabled', false);
})

@Kichrum이 제공 한 솔루션은 거의 저에게 효과적이었습니다. 기본 동작을 방지하기 위해 e.stopImmediatePropagation ()도 추가해야했습니다. 내 코드는 다음과 같습니다.

$('a, button').on('click', function (e) {
    var $link = $(e.target);
    if (!$link.data('lockedAt')) {
        $link.data('lockedAt', +new Date());
    } else if (+new Date() - $link.data('lockedAt') > 500) {
        $link.data('lockedAt', +new Date());
    } else {
        e.preventDefault();
        e.stopPropagation();
        e.stopImmediatePropagation();
    }
});

정말로 원하는 것이 두 번 클릭을 막는 것이 아니라 여러 양식 제출을 피하는 것이라면 버튼의 클릭 이벤트에 jQuery one ()을 사용하는 것이 클라이언트 측 유효성 검사 (예 : 필수로 표시된 텍스트 필드)가있는 경우 문제가 될 수 있습니다. 클릭이 클라이언트 측 유효성 검사를 트리거하고 유효성 검사가 실패하면 버튼을 다시 사용할 수 없기 때문입니다. 이를 방지하기 위해 one ()을 양식의 제출 이벤트에서 직접 사용할 수 있습니다. 이것은 내가 찾은 가장 깨끗한 jQuery 기반 솔루션입니다.

<script type="text/javascript">
$("#my-signup-form").one("submit", function() {
    // Just disable the button.
    // There will be only one form submission.
    $("#my-signup-btn").prop("disabled", true);
});
</script>

참조 URL : https://stackoverflow.com/questions/11621652/how-to-prevent-a-double-click-using-jquery

반응형