jquery stopPropagation problem with live method

前端 未结 3 1275
灰色年华
灰色年华 2021-01-13 10:57

Jquery stopPropagation method dosen\'t work with live method. Below the code is works fine with click instead of live method. Any help greatly appreciated.

Code:<

3条回答
  •  旧巷少年郎
    2021-01-13 11:19

    You just need to change the order of your handlers a bit, and use/check for propagation stopping, like this:

    $("a.infolink").live("click",function(e){
        $("a.infolink").removeClass("selected");
        $("div.infomenu").hide();
        $(this).addClass("selected");
        $(this).next().show();
        e.stopPropagation();
    });
    $("div.infomenu").live("click",function(e){
        e.stopPropagation();
    });
    $(document).click(function(e){
        if(e.isPropagationStopped()) return;  //important, check for it!
        $("a.infolink").removeClass("selected");
        $("div.infomenu").hide();
    });
    $("input.clickme").click(function(e){
        alert("I am fired");
    });​
    

    Give it a try here, there are a few important points to keep in mind:

    • .live() handlers are on document
    • Event handlers execute in the order they were bound to any given element

    You need to stop and check the propagation since we're at the same level. .stopPropagation() would prevent the bubbling from going any higher but that doesn't matter, it's at the same level in the DOM, so you need to check if it was stopped, using .isPropagationStopped(). Also, since the handlers fire in order, you need to bind that document.onclick after your other event handlers, otherwise it'll execute first, before the others tried to stop propagation.

提交回复
热议问题