jQuery 选择器(仅选择目标,不选择后代)

标签 jquery jquery-mobile jquery-selectors

我只想将事件绑定(bind)到 jQuery 中的“页面”。 问题是,当使用 addClass 时,代码不仅针对“页面”执行,而且针对所有后代执行。我想仅当 addClass 用于“pages”div 时触发该事件。我怎样才能做到这一点?

//https://stackoverflow.com/a/31859060/2947462
(function( func ) {
    $.fn.addClass = function() { // replace the existing function on $.fn
        func.apply( this, arguments ); // invoke the original function
        this.trigger('eventAddClass'); // trigger the custom event
        return this; // retain jQuery chainability
    }
})($.fn.addClass); // pass the original function as an argument


$(document).on( "eventAddClass", 'div[data-role="page"]', function(event) {
    //code - do some stuff
});

最佳答案

你可以这样做。

这就是事件冒泡。读这个~https://www.sitepoint.com/event-bubbling-javascript/

$(document).on( "eventAddClass", 'div[data-role="page"]', function(event) {
    if(event.target !== event.currentTarget) return;

    // your custom code
});

关于jQuery 选择器(仅选择目标,不选择后代),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52221055/

相关文章:

jquery - ASP.NET Jquery 自动完成

Jquery Keyup 函数之间的延迟

javascript - 在javascript中确定 future 的年龄

css - 如何在 jQuery Mobile 输入中添加 bootstrap 之类的前缀?

ajax - 如何使用来自服务器的JSON数据填充jQuery Mobile ListView ?

jquery - 使用 ember.js 和 ember easyform 包装 bootstrap/jquery 小部件

jquery - jquery mobile 中一键关闭和打开弹出窗口

javascript - 如何使用 jQuery 克隆和追加多个元素?

javascript - 复杂的jquery选择器: challenge

javascript - Jquery,从条件中获取 'this' 选择器