program story

jQuery Button.click () 이벤트가 두 번 트리거됩니다.

inputbox 2020. 10. 20. 07:37
반응형

jQuery Button.click () 이벤트가 두 번 트리거됩니다.


이 코드에 다음과 같은 문제가 있습니다.

<button id="delete">Remove items</button>

$("#delete").button({
     icons: {
             primary: 'ui-icon-trash'
     }
}).click(function() {
     alert("Clicked");
});

이 버튼을 클릭하면 경고가 두 번 표시됩니다. 이 특정 버튼뿐만 아니라 내가 만드는 모든 버튼이 있습니다.

내가 도대체 ​​뭘 잘못하고있는 겁니까?


현재 코드가 작동하며 여기에서 시도해 볼 수 있습니다. http://jsfiddle.net/s4UyH/

다른 것을 트리거하는 예제 외부에 무언가 .click()있습니다click . 해당 요소 에서 이벤트를 트리거하는 다른 핸들러도 확인하십시오 .


이 경우 다음을 수행 할 수 있습니다.

$('selected').unbind('click').bind('click', function (e) {
  do_something();
});

처음에는 이벤트가 두 번 실행되고 페이지가 새로 고쳐지면 네 번 실행됩니다. 내가 구글 검색으로 알아 내기까지 많은 시간이 지나지 않았다.

또한 JQueryUI 아코디언 위젯을 사용하기 시작할 때까지 코드가 처음에 작동했다고 말해야합니다.


나도 경험 한 이상한 행동. 그래서 나를 위해 "거짓 반환"이 트릭을했습니다.

        $( '#selector' ).on( 'click', function() {
            //code
            return false;
        });

사용하는 경우

$( document ).ready({ })

또는

$(function() { });

두 번 이상 클릭 기능은 사용되는 횟수만큼 트리거됩니다.


당신은 이것을 시도 할 수 있습니다.

    $('#id').off().on('click', function() {
        // function body
    });
    $('.class').off().on('click', function() {
        // function body
    });

나는 같은 문제가 있었고 모든 것을 시도했지만 작동하지 않았습니다. 그래서 다음 트릭을 사용했습니다.

function do_stuff(e)
{
    if(e){ alert(e); }
}
$("#delete").click(function() {
    do_stuff("Clicked");
});

해당 매개 변수가 코드를 작성하는 것보다 null이 아닌지 확인합니다. 따라서 함수가 두 번째로 트리거되면 원하는 것을 표시합니다.


이것은뿐만 아니라 모두를함으로써 트리거 될 수 있습니다 inputlabel 내부에 클릭 리스너를 가진 요소.

당신은 클릭 label클릭 이벤트를 트리거하는, 그리고 뿐만 아니라 온 또 다른 클릭 이벤트 input에 대한 label. 두 이벤트 모두 요소에 버블 링됩니다.

멋진 CSS 전용 토글 펜 : https://codepen.io/stepanh/pen/WaYzzO

참고 : 이것은 jQuery와 관련된 것이 아니며 기본 리스너는 펜에 표시되는 것과 같이 2x 트리거됩니다.


$("#id").off().on("click", function() {

});

나를 위해 일했습니다.

$("#id").off().on("click", function() {

});

두 번 이상 발생하는 함수에서 element.click을 바인딩하면 대기열에 추가되므로 다음에 클릭하면 바인딩 함수가 실행 된 횟수만큼 트리거됩니다. 신참 실수는 아마 내쪽에 있지만 도움이되기를 바랍니다. TL, DR : 한 번만 발생하는 설정 기능에 대한 모든 클릭을 바인딩해야합니다.


Nick이 말하려는 것처럼 외부의 무언가가 이벤트를 두 번 트리거합니다. 이를 해결하려면 event.stopPropagation ()을 사용하여 부모 요소가 버블 링되지 않도록해야합니다.

$('button').click(function(event) {
    event.stopPropagation();
});

이게 도움이 되길 바란다.


제 경우에는 이런 식으로 변경 명령을 사용했습니다.

$(document).on('change', '.select-brand', function () {...my codes...});

and then i changed the way to

$('.select-brand').on('change', function () {...my codes...});

and it solved my problem.


This can be caused for following reasons:

  1. Either you have included the script more than once in the same html file
  2. You already added the event listener using onclick attribute on the element
  3. If you use template inheritance like extends in django, most probably you have included the script in more than one file which are combined together by include or extend
  4. The event is bubbled up to some parent element.
  5. If you are using django template, you have wrongly placed a block inside another.

So, you should either find them out and remove the duplicate import. It is the best thing to do.

Another solution is to remove all click event listeners first in the script like:

$("#myId").off().on("click", function(event) {
event.stopPropagation();
});

You can skip event.stopPropagation(); if you are sure event is not bubbled.

참고URL : https://stackoverflow.com/questions/3070400/jquery-button-click-event-is-triggered-twice

반응형