JQuery use: not selector with on

Having a bit of trouble. Please take a look at the following code.

$(document).on("click", "*:not(.parent-container a)", function(e) {
    // Do stuff if we have not clicked a link inside .parent-container
});

.parent-container is appended to the DOM. Then we want to bind a “click” event everywhere but to the links inside of .parent-container, but I am finding that when I click the links inside of .parent-container that “Do stuff if we have not clicked a link inside .parent-container” is still executing.

Any advice as to how to correctly avoid binding to “.parent-container a”?

Usually the right practice is to have two bindings (in fact, as your real application already have more bindings, and probably ones for the a elements, you don’t add bindings, you just add the return false
) :

$(document).on("click", function(e) {
    // Do stuff if we have not clicked a link inside .parent-container
}).on("click", ".parent-container a", function(e) {
    // you probably already have something to do
    return false; // avoid propagation, the other event handler won't be called
});

Demonstration

Hello, buddy!稿源:Hello, buddy! (源链) | 关于 | 阅读提示

本站遵循[CC BY-NC-SA 4.0]。如您有版权、意见投诉等问题,请通过eMail联系我们处理。
酷辣虫 » 前端开发 » JQuery use: not selector with on

喜欢 (0)or分享给?

专业 x 专注 x 聚合 x 分享 CC BY-NC-SA 4.0

使用声明 | 英豪名录