0

私はHTMLスニペットを持っています

  <div class="playlist" id='{{ playlist.name }}'>
         {{ playlist.name }} 
        <button class="btn btn-primary queueAll" href="#">queue all</button> 
        <i class="icon-chevron-right icon-large"></i>
   </div>

および対応するjQuery関数として

$(function(){
    $('#playlist').click(function(){
        $.ajax({
            url: '/getUserPlaylists',
            success: function(response, textStatus, jqXHR){
                // console.log(response);
                $('#feature').empty().append(response);
            },
            error: function(response, textStatus, jqXHR) {
                bootstrap_alert.error('error in receving playlists');
            }
        });
    });
});

私が欲しいもの

  • ユーザーがqueue allボタンをクリックすると、alertポップアップが表示され、何も起こりません

そのための私のjQuery機能は

$(function(){
    $('body').on('click', '.queueAll', function(e) {
        e.preventDefault();
        alert('will queue all videos');
    });
});

今何が起きているのですか?

私はそうしますalert 'will queue all videos'が、最初の関数にリストされているように ajax 呼び出しを行いjQuery、次のページに結果をロードします

期待どおりに機能しないのはどうしてe.preventDefault()ですか?

4

2 に答える 2

1

第一に、ボタンに href 属性を持たせるべきではありません。第二に、 preventDefault は要素のデフォルト アクションを防ぎます。リンクが href の URL にリダイレクトされるのを防ぎます。フォームが送信されるのを防ぎます。JavaScript に関連付けられたイベント ハンドラーは妨げられません。そのため、ハンドラーのバインドを解除する必要があります。

ID の要素もターゲットにしていますplaylistが、プレイリスト名が単にplaylist?でない限り、それはクラスのようです。

動的でない限り、次のようなものかもしれません:

$(function(){
    $('.queueAll').on('click', function(e) {
        alert('will queue all videos');
        return false;
    });
});

また :

$(function(){
    $('#playlist').click(function(e){
        if (e.target.tagName !== 'BUTTON') { //make sure it's not the button
            $.ajax({
                url: '/getUserPlaylists',
                success: function(response, textStatus, jqXHR){
                    // console.log(response);
                    $('#feature').empty().append(response);
                },
                error: function(response, textStatus, jqXHR) {
                    bootstrap_alert.error('error in receving playlists');
                }
            });
        }
    });
});
于 2012-08-16T23:32:02.970 に答える
0

あなたが求めているのは、実際e.stopPropagation()には、イベントが親にバブリングするのを止めることだと思います。

編集:Adam が指摘するようにon()、イベントを使用して実際にボタンではなく body 要素にアタッチしているため、コードが起動すると、イベントは #playlist 要素を通過して既にバブリングされています。

代わりに、ターゲット (event.target) がボタンの場合 (または#playlist 要素ではない場合)、#playlist クリック ハンドラーをチェックインする必要があると思います。

$('#playlist').click(function(e){
    if ($(e.target).is('#playlist')) {
        // Do stuff here as it was the #playlist element that was clicked - NOT a child of it
    }
});
于 2012-08-16T23:30:27.070 に答える