25

これがシナリオです。私のコンテンツはクラスに基づいて非同期に読み込まれます。したがって、クラスajaxLinkとのリンクがある場合、次のように起動します。

$('a.ajaxLink').click(function (e) {
        e.preventDefault();
        var container = $(this).parents('div.fullBottomContent');
        var href = $(this).attr('href');
        container.fadeOut('fast', function () {
            $.ajax({
                url: href,
                dataType: "html",
                type: "GET",
                success: function (data) {
                    container.html(data);
                    BindEventHandlers();
                    container.fadeIn();
                    $.validator.unobtrusive.parse('form');
                },
                error: function () {
                    alert('An error has occurred');
                }
            });
        });

    });

すべて素敵です。confirmある例では、ユーザーがページをロードしてすべての変更を失いたいという警告をユーザーに表示したいので、次のように記述しました。

$('a.addANewHotel').click(function (e) {
        if (!confirm('Adding a new hotel will loose any unsaved changes, continue?')) {
            e.stopPropagation();
        }
    });

今私は試しましreturn falseたがe.preventDefault()e.stopPropagation();最初のメソッドが常に実行されても?余分なクリックイベントが発生しないようにするにはどうすればよいですか?これはイベントの順序ですか?

これがどのように関連しているかわかりませんが、私のHTMLは次のとおりです。

<a style="" href="/CMS/CreateANewHotel?regionID=3&amp;destinationID=1&amp;countryName=Australia" class="button wideBorderlessButton ajaxLink addANewHotel">Add a new hotel</a>
4

2 に答える 2

49

試しましたか:event.stopImmediatePropagation

私はそれがあなたが探しているものだと信じています:

http://api.jquery.com/event.stopImmediatePropagation/

$('a.addANewHotel').click(function (e) {
        if (!confirm('Adding a new hotel will loose any unsaved changes, continue?')) {
            e.stopImmediatePropagation();
            e.preventDefault();
        }
    });
于 2012-10-03T12:53:31.750 に答える
3

stopPropagationイベントが親要素にバブリングするのを防ぎ、同じ要素の他のクリックハンドラーが発生するのを防ぎません。したがって、ソリューションは機能しません。

たとえば、次のように実行できます。

$('a.ajaxLink').click(function (e) {
    e.preventDefault();

    if($(this).hasClass("a.addANewHotel") &&
           !confirm('Adding a new hotel will loose any unsaved changes, continue?')){
        return false;
    }

    var container = $(this).parents('div.fullBottomContent');
    var href = $(this).attr('href');
    container.fadeOut('fast', function () {
        $.ajax({
            url: href,
            dataType: "html",
            type: "GET",
            success: function (data) {
                container.html(data);
                BindEventHandlers();
                container.fadeIn();
                $.validator.unobtrusive.parse('form');
            },
            error: function () {
                alert('An error has occurred');
            }
        });
    });

});

さまざまな種類のリンクがある場合は、共通のコードを関数に配置し、差別化クラスを使用してハンドラーをバインドする必要があります。これらのハンドラーは、必要に応じて共通コードを呼び出すことができます。

于 2012-10-03T12:52:27.847 に答える