按钮点击事件仅在重新加载页面或在功能

时间:2017-04-13 12:15:28

标签: javascript jquery

我的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));
                }
            });
        }
    });
}

1 个答案:

答案 0 :(得分:1)

 $(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();
        }
    });
});