2

$(document).bind() を使用して、ページのすべての要素にイベント ハンドラーをバインドしています。

特定の要素に対してこのハンドラーのバインドを解除する方法を知っている人はいますか?

これは、私が望むように動作しない私のサンプルコードです:

<html><head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.js">    </script>
</head>
<body>
    <div id="mid" style="cursor:pointer" >click me</div>
    <div>sample</div>
    <script type="text/javascript">
        var fun = function() {
            alert('default handler');
        };
        $(document).bind('click.custom', fun);
        //trying to unbind the handler but it remains there
        $("#mid").unbind('click.custom');
    </script>
</body>
</html>

ここでダニエルの答えを考えると、この問題が再び発生します。

var ff = function() {
    alert('additional');
}

$(document).bind('click.custom', fun);
$(document).bind('click.custom2', ff);
$("#mid").bind('click.custom', false); 

ここで fun イベント ハンドラーは #mid 要素から完全にバインド解除されましたが、ff イベント ハンドラーもバインド解除されました。これは私にとって問題です。

4

2 に答える 2

1

イベントバブリングと呼ばれます。ネストされた要素のイベントは、親まで上がります。

そのハンドラーに行き、そこから戻る必要bindがあります。#midfalse

于 2011-03-16T00:27:49.470 に答える
0

ドキュメントにバインドされたイベントは 1 つだけです。バブリングのため、イベントは、伝播が停止するかドキュメントに到達するまで、DOM 階層を上って送信されます。

コールバックを変更してこのイベントが から来た場合は無視するか、#mid組み込みのデリゲート/ライブを使用して同じ効果を得ることができます。

$(document).delegate('[id!="mid"]', 'click.custom', fun);

これにより、ID「mid」を持つ要素からのイベントが無視されます。もう 1 つの方法は、関数自体を変更することです。

function fun() {
    if (this.id == "mid") { 
        return; // if event came from #mid, ignore it.
    }
    // continue processing as normal
}
于 2011-03-16T00:41:15.813 に答える