Attaching jQuery event handlers so that they are triggered first

前端 未结 9 1848
太阳男子
太阳男子 2020-12-05 09:36

Is there a way to attach a jQuery event handler such that the handler is triggered before any previously-attached event handlers? I came across this article, but the code d

9条回答
  •  余生分开走
    2020-12-05 10:04

    I create a very simple function to put my click event handler at first position, and all existing click handlers will only be triggered manually.

    $.fn.bindClickFirst = function (eventHandler) {
        var events = $._data($next[0], "events");
        var clickEvtHandlers = [];
    
        events.click.forEach(function (evt) {
            clickEvtHandlers.push(evt.handler);
        });
        $next.off("click");
    
        $next.on("click", function () {
            var evtArg = event;
            eventHandler(evtArg, function () {
                clickEvtHandlers.forEach(function (evt) {
                    evt(evtArg);
                });
            });
        })
    }
    

    And to use the function:

    $btn.bindClickFirst(function (evt, next) {
        setTimeout(function () {
            console.log("bbb");
            next();
        }, 200)
    })
    

提交回复
热议问题