找出事件目标是否是已知元素的子元素的最有希望的方法是什么?

时间:2015-07-09 20:42:25

标签: javascript html css jqlite jquery-events

我可以访问我的父元素:

var parentElem = angular.element('#parent');

然后在下面的点击事件中,我想检查点击是否由上述父母的任何孩子生成。

$('html').click(function (e) {

  // check e.target is child of 'parentElem'           

});

1 个答案:

答案 0 :(得分:1)

你应该能够用普通的JavaScript来实现这个目标:

// Get a reference to a raw DOM node
var parentElem = angular.element("#parent")[0];

$("html").click(function(e) {
    // Get a reference to the event target
    var element = e.target;

    // "Climb" up the document tree until you've found the parent,
    // or you can "climb" up no further.
    while (parentElem !== element && element.parentNode) {
        element = element.parentNode;
    }

    if (element === parentElem) {
        // event target is inside parentElem
    }
    else {
        // event target is not a child of parentElem
    }
});