开发者

Jquery rebind click after unbinding

I've got an element inside a div which has a click event associated to it. Both click events work fine, except they both fire at the same time.

When I click on the inner element to disable the parent div's click event:

My html (inside a @foreach MVC Razor loop):

<td class="tdfuncLangSignOff tdNotChecked tdLang@(item.Language.Name)" title="@(item.SignedOffStatus)">
    <div class="addComment"></div>
    @Html.Hidden("funcSignOffId", item.Id)
</td>

My jquery:

var handler = function () {
    var thisTD = $(this);
    var signOffId = thisTD.parent().children("input#funcSignOffId").val();
    console.log("parent div click");
}

    $(".tdfuncLangSignOff").click(handler);

$(".addComment").click(function () { 
    $(this).parent().unbind("click")
    console.log("nested div click");
    //$(this).parent().click(handler)
});

I found the handler idea from this thread

This allows me to click on the addComment div and disable the click on the parent div as I wanted. But the rebinding obviously doesn't happen. When I uncomment $(this).parent().click(handler) in the addComment click function the click triggers and the console displays "parent div click".

How can I rebind the click of the pare开发者_运维问答nt div without having it triggered immediately?


If I understand you properly: In order to stop propagation of the event, use event.stopPropagation().

example:

<div id="a">
    Outer
    <div id="b">Inner</div>
<div>

and in JQuery:

$("#a").click(function(event) {alert("a");});
$("#b").click(function(event) {alert("b"); event.stopPropagation();});

You can read more here: http://api.jquery.com/event.stopPropagation/


I suspect the reason is because you are rebinding the click handler in the child click event, and THEN the event propagates to the next level (its parent), which now has the click handler again.

Unless I'm missing something else, Naor's advice with stopping propagation should serve your purpose.


You can try:

$(this).parent().bind('click');
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜