2

I am trying to detect whether a target element is either a child element, or the same element, that I have as an object reference.

I am using the following logic:

$("html").on("mousewheel.scroll DOMMouseScroll.scroll",function(e){
   e.preventDefault();

   var $scrollableElement = $(".foo").eq(0);
   var $target = $(e.target);

   if ($target == $scrollableElement
       || $target.parents($scrollableElement).length) {                
        alert("scroll");                    
   }

});  

However "scroll" is alerted even when scrolling over an element which is neither .foo or a child of .foo.

In my JsFiddle example, scroll over the .bar element, and "scroll" is still alerted:

http://jsfiddle.net/Lf3d2/

Why is this? Is it possible to use jQuery object references as the selector of .parents()?

4

1 回答 1

6

尝试.closest()而不是.parents()

$(function () {

    var $scrollableElement = $(".foo").eq(0);
    $("html").on("mousewheel.scroll DOMMouseScroll.scroll", function (e) {
        e.preventDefault();

        var $target = $(e.target);

        if ($target.closest($scrollableElement).length) {
            console.log("scroll");
        }

    });

});

演示:小提琴

如果您查看.parents()的语法,它不会将 jQuery 对象作为参数。唯一允许的语法是.parents( [selector ] )


.foo正如@ A.Wolff询问为什么不将事件绑定到

演示:小提琴

于 2014-04-07T09:13:46.177 回答