programing

클릭 이벤트가 자녀가 아닌 부모 DIV에게만 불을 지르는 방법은?

telebox 2023. 5. 22. 20:56
반응형

클릭 이벤트가 자녀가 아닌 부모 DIV에게만 불을 지르는 방법은?

등급이 지정된 DIV가 있습니다.foobar그리고 그 DIV 안에 분류되지 않은 DIV 몇 개가 있지만, 나는 그들이 상속받고 있다고 생각합니다.foobar클래스:

$('.foobar').on('click', function() { /*...do stuff...*/ });

나는 그것이 DIV의 어딘가를 클릭할 때만 작동하고 아이들 DIV에서는 작동하지 않기를 원합니다.

만약에e.target와 동일한 요소입니다.this하위 항목을 클릭하지 않았습니다.

$('.foobar').on('click', function(e) {
  if (e.target !== this)
    return;
  
  alert( 'clicked the foobar' );
});
.foobar {
  padding: 20px; background: yellow;
}
span {
  background: blue; color: white; padding: 8px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class='foobar'> .foobar (alert) 
  <span>child (no alert)</span>
</div>

저는 일에 대한 승인된 답변을 받지 못했지만, 적어도 바닐라 JS에서는 이것이 효과가 있는 것 같습니다.

if(e.target !== e.currentTarget) return;

최신 브라우저만 대상으로 삼는 것을 꺼리지 않는다면 작동하는 또 다른 방법이 있습니다.CSS만 추가하면 됩니다.

pointer-events: none;

클릭을 캡처할 디브의 모든 아이들에게.다음은 지원 테이블입니다.

http://caniuse.com/ #http=http-session

버블링을 원하는 대로 사용할 수 있습니다.

$('.foobar').on('click', function(e) {
    // do your thing.
}).on('click', 'div', function(e) {
    // clicked on descendant div
    e.stopPropagation();
});
//bind `click` event handler to the `.foobar` element(s) to do work,
//then find the children of all the `.foobar` element(s)
//and bind a `click` event handler to them that stops the propagation of the event
$('.foobar').on('click', function () { ... }).children().on('click', function (event) {
    event.stopPropagation();
    //you can also use `return false;` which is the same as `event.preventDefault()` and `event.stopPropagation()` all in one (in a jQuery event handler)
});

그러면 시스템의 전파(버블링)가 중지됩니다.click모든 하위 요소에 대한 이벤트.foobar이벤트가 이벤트에 도달하지 않도록 하는 요소.foobar이벤트 핸들러를 실행하는 요소입니다.

여기 데모가 있습니다. http://jsfiddle.net/bQQJP/

저도 같은 문제가 있었고 이 해결책을 생각해냈습니다(다른 답변을 바탕으로).

 $( ".newsletter_background" ).click(function(e) {
    if (e.target == this) {
        $(".newsletter_background").hide();
    } 
});

기본적으로 대상이 div이면 코드를 실행하고 그렇지 않으면 아무것도 하지 않습니다(숨기지 마십시오).

$(".advanced ul li").live('click',function(e){
    if(e.target != this) return;
    //code
    // this code will execute only when you click to li and not to a child
})

event.currentTarget을 사용할 수 있습니다.클릭 이벤트는 이벤트를 받은 요소만 수행합니다.

target = e => {
    console.log(e.currentTarget);
  };
<ul onClick={target} className="folder">
      <li>
        <p>
          <i className="fas fa-folder" />
        </p>
      </li>
    </ul>

사용할 수 없는 경우pointer-events: none;그리고 당신이 사용할 수 있는 최신 브라우저를 목표로 하고 있습니다.composedPath다음과 같이 개체에서 직접 클릭을 감지합니다.

element.addEventListener("click", function (ev) {
    if (ev.composedPath()[0] === this) {
        // your code here ...
    }
})

composedPath에 대한 자세한 내용은 https://developer.mozilla.org/en-US/docs/Web/API/Event/composedPath 에서 확인할 수 있습니다.

내 경우도 비슷하지만 당신이 거의 없는 경우입니다.foobar-s. 한 번 클릭할 때마다 한 번씩만 닫으려고 하는 경우:

상위 사례 찾기

$(".foobar-close-button-class").on("click", function () {
    $(this).parents('.foobar').fadeOut( 100 );
    // 'this' - means that you finding some parent class from '.foobar-close-button-class'
    // '.parents' -means that you finding parent class with name '.foobar'
});

하위 케이스 찾기

$(".foobar-close-button-class").on("click", function () {
    $(this).child('.foobar-close-button-child-class').fadeOut( 100 );
    // 'this' - means that you finding some child class from '.foobar-close-button-class'
    // '.child' -means that you finding child class with name '.foobar-close-button-child-class'
});

이벤트를 정의하면 이벤트에 속성이 있습니다.this이 속성은 이벤트가 할당된 DOM 요소를 나타냅니다.이벤트가 발생한 요소를 확인하려면 다음을 사용합니다.e.target.

이벤트는 요소의 자식에서 상속되므로 대상이

function doSomething(event) {
  if (this == event.target){
    // do something
  }
}

// if its li get value 
document.getElementById('li').addEventListener("click", function(e) {
                if (e.target == this) {
                    UodateNote(e.target.id);
                }
                })
                
                
                function UodateNote(e) {

    let nt_id = document.createElement("div");
    // append container to duc.
    document.body.appendChild(nt_id);
    nt_id.id = "hi";
    // get conatiner value . 
    nt_id.innerHTML = e;
    // body...
    console.log(e);

}
li{
 cursor: pointer;
    font-weight: bold;
  font-size: 20px;
    position: relative;
    width: 380px;
    height: 80px;
    background-color: silver;
    justify-content: center;
    align-items: center;
    text-align: center;
    margin-top: 0.5cm;
    border: 2px solid purple;
    border-radius: 12%;}
    
    p{
     cursor: text;
  font-size: 16px;
   font-weight: normal;
    display: block;
    max-width: 370px;
    max-height: 40px;
    overflow-x: hidden;}
<li id="li"><p>hi</p></li>

언급URL : https://stackoverflow.com/questions/9183381/how-to-have-click-event-only-fire-on-parent-div-not-children

반응형