【问题标题】:jQuery selectors (select only target, without descendants)jQuery 选择器(只选择目标,没有后代)
【发布时间】:2019-02-12 17:16:28
【问题描述】:

我只想将事件绑定到 jQuery 中的“页面”。 问题是代码不仅针对“页面”执行,而且在使用addClass 时针对所有后代执行。我只想在addClass 用于“页面”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
});

【问题讨论】:

    标签: jquery jquery-mobile jquery-selectors


    【解决方案1】:

    你可以这样做。

    这是事件冒泡。看这篇~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
    });
    

    【讨论】:

    • 事件冒泡不会影响所有ascendants,而不是后代?还是 OP 只是使用了错误的术语?
    • @freedomn-m 我只是说这是事件冒泡的一部分。它是冒泡的一部分吗?
    猜你喜欢
    • 1970-01-01
    • 2011-03-31
    • 1970-01-01
    • 1970-01-01
    • 2017-09-17
    • 1970-01-01
    • 2017-05-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多