简体   繁体   English

Jquery:元素上的事件选择器而不是其子级上的事件?

[英]Jquery: selector for an event on an element but not on its children?

I would like to know if this is possible, with a jquery selector, to bind an event on an element but not on its children.我想知道这是否可能,使用 jquery 选择器将事件绑定到元素而不是其子元素。 Actually, I have two divs one on the other, in absolute position, and I would like to detect the same event on the two divs, but not if the event is happening on a child of the top div (I mean, I would like to detect if the event is on the transparent parts of the top div, as if it was happening on the lower div).实际上,我有两个 div 一个在另一个上,绝对是 position,我想在两个 div 上检测到相同的事件,但如果事件发生在顶部 div 的子级上则不会(我的意思是,我想检测事件是否在顶部 div 的透明部分,就好像它发生在下部 div 上一样)。

for example, here, #desktop and #apps are one on the other, with the same fixed width and height, and I would like to detect an event on: #desktop, or on #apps, but not on.stuff例如,在这里,#desktop 和 #apps 是一个在另一个上,具有相同的固定宽度和高度,我想检测一个事件:#desktop 或 #apps,但不是 on.stuff

HTML HTML

<div id="desktop">

</div>
<div id="apps">
    <div class="stuff">
        test
    </div>
    <div class="stuff">
        test2
    </div>
</div>

JavaScript JavaScript

$("#desktop, #global:not(its_CHildren?)").mousemove(function (mouse){
    // ...
}

If this is not possible with a selector, I was thinking of doing something like this, which works satisfiyingly:如果选择器无法做到这一点,我正在考虑做这样的事情,它的效果令人满意:

$("#desktop, #apps").mousemove(function(mouse){
    $("#global stuff").mousemove(function() {
        return false;
    });
    // ...
});

The handlers are only bound to the parent elements.处理程序仅绑定到父元素。 The issue is that the events bubble up from the descendants, and fire the handler attached to the parent.问题是事件从后代中冒出来,并触发附加到父级的处理程序。

You could test the event.target to see if it is the same value as this (the element to which the handler is bound).您可以测试event.target以查看它是否与this (处理程序绑定到的元素)的值相同。

$("#desktop, #apps").mousemove(function(e){
     if( e.target === this ) {
        //run your code
     }
});

Example: http://jsfiddle.net/KAJhe/ (open your console to see when the code logs the ID of the hovered element)示例: http://jsfiddle.net/KAJhe/ (打开控制台查看代码何时记录悬停元素的 ID)

Now the code in the if will only fire when you're not moving the mouse over a parent, but not over a descendant element.现在if中的代码只会在您没有将鼠标移到父元素上而不是后代元素上时触发。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM