Programing

jQuery는 1 div를 제외한 페이지의 아무 곳이나 클릭합니다.

lottogame 2020. 10. 18. 08:22
반응형

jQuery는 1 div를 제외한 페이지의 아무 곳이나 클릭합니다.


한 div ( id=menu_content)를 제외하고 내 페이지의 아무 곳이나 클릭 할 때 함수를 트리거하려면 어떻게 해야합니까?


id를 가진 div에 의해 이벤트가 생성 되면 문서 click적용 body하고 click처리를 취소 할 수 있습니다 . 이것은 이벤트를 단일 요소에 바인딩 하고 다음을 제외한 모든 요소에 바인딩을 저장합니다.clickmenu_contentclickmenu_content

$('body').click(function(evt){    
       if(evt.target.id == "menu_content")
          return;
       //For descendants of menu_content being clicked, remove this check if you do not want to put constraint on descendants.
       if($(evt.target).closest('#menu_content').length)
          return;             

      //Do processing of click event here for every element except with id menu_content

});

jQuery Event Target 문서를 참조하십시오 . 이벤트 객체의 target 속성을 사용하면 #menu_content요소 내에서 클릭이 발생한 위치를 감지 할 수 있으며, 그렇다면 클릭 핸들러를 일찍 종료 할 수 있습니다. .closest()클릭이의 하위 항목에서 시작된 경우를 처리하는 데 사용해야 합니다 #menu_content.

$(document).click(function(e){

    // Check if click was triggered on or within #menu_content
    if( $(e.target).closest("#menu_content").length > 0 ) {
        return false;
    }

    // Otherwise
    // trigger your click function
});

이 시도

 $('html').click(function() {
 //your stuf
 });

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

외부 이벤트 를 사용할 수도 있습니다.


나는이 질문에 대한 답을 알고 있으며 모든 답이 훌륭합니다. 그러나 나는 비슷한 (정확히 같은 것은 아님) 문제를 가진 사람들을 위해이 질문에 2 센트를 더하고 싶었습니다.

보다 일반적인 방법으로 다음과 같이 할 수 있습니다.

$('body').click(function(evt){    
    if(!$(evt.target).is('#menu_content')) {
        //event handling code
    }
});

이렇게하면 id menu_content가있는 요소를 제외한 모든 요소에 의해 발생한 이벤트뿐만 아니라 CSS 선택기를 사용하여 선택할 수있는 요소를 제외한 모든 요소에 의해 발생한 이벤트도 처리 할 수 ​​있습니다.

예를 들어 다음 코드 스 니펫 <li>에서 id를 가진 div 요소의 자손 인 모든 요소를 제외한 모든 요소에 의해 이벤트가 시작됩니다 myNavbar.

$('body').click(function(evt){    
    if(!$(evt.target).is('div#myNavbar li')) {
        //event handling code
    }
});

여기 내가 한 일이 있습니다. 내 datepicker를 닫지 않고 자녀를 클릭 할 수 있는지 확인하고 싶었습니다.

$('html').click(function(e){
    if (e.target.id == 'menu_content' || $(e.target).parents('#menu_content').length > 0) {
        // clicked menu content or children
    } else {
        // didnt click menu content
    }
});

내 실제 코드 :

$('html').click(function(e){
    if (e.target.id != 'datepicker'
        && $(e.target).parents('#datepicker').length == 0
        && !$(e.target).hasClass('datepicker')
    ) {
        $('#datepicker').remove();
    }
});

참고URL : https://stackoverflow.com/questions/12661797/jquery-click-anywhere-in-the-page-except-on-1-div

반응형