我的HTML页面上的几个按钮似乎仅在事件功能中存在alert时,或者在导航至另一个页面然后返回首页时才起作用。从我读过的其他类似问题中,似乎主页正在尝试完成某些任务,而警报似乎在花更多时间。但是,我不确定我的情况是否如此。

我有一个Javascript文件actions.js,该文件由HTML页中的标头作为源加载。该文件如下(仅显示相关代码):

$(document).ready(function() {
    //This function only works with an alert before the Ajax call or when page is reloaded
    $("button[name='delete_deck']").click(function() {
        var id = this.id;

        $.ajax({
            url: "delete_decks.php",
            type: "GET",
            data: {selection:JSON.stringify(id)},
            async: false,
            success: function(data) {
                location.reload();
            }
        });
    });

    //This function is for a button on the same page, but works fine without the alert or reloading the page
    $("#study").click(function() {
        var selection = getDeckSelections();

        if(selection.length > 0) {
            //Get the selected side of the card
            var selected_side = $('input[name=side_selection]:checked', '#side_selection_form').val();

            //Store the selected side in session storage
            sessionStorage.setItem("selected_side", selected_side);

            //Ajax call to get cards from database
            $.ajax({
                url: "get_cards.php",
                type: "GET",
                data: {selection:JSON.stringify(selection)},
                cache: false,
                async: false,
                success: function(data) {
                    json = JSON.parse(data);
                    //Store the cards in session storage
                    sessionStorage.setItem("cards", JSON.stringify(json));
                }
            });
        }
    });
}

最佳答案

 $(document).on('click',"button[name='delete_deck']",function() {
    var id = this.id;

    $.ajax({
        url: "delete_decks.php",
        type: "GET",
        data: {selection:JSON.stringify(id)},
        async: false,
        success: function(data) {
            location.reload();
        }
    });
});

10-05 20:43
查看更多