首页 > 解决方案 > 链接上的 e.preventDefault() 仍会加载页面

问题描述

标题可能有点误导,但我不知道如何更好地表达它,所以我为此道歉。

我正在创建一个自定义处理程序,以便在按下新内容时网站不会刷新(例如,类似于 youtube 的工作方式)。

为此,我正在使用此脚本:

$('.sidebar2 li a').click(function (e) {
    test = true;
    var button = $(this);
    var noteId = button.data("noteid");

    $(".sidebar2 li.active").removeClass("active");
    var postData = { id: noteId };
    $.ajax({
        url: '/API/Note',
        type: 'get',
        data: postData,
        success: function (resp) {
            if (resp.success == true) {
                $('#app-bar-left').html(resp.note.navBarHTML);
                $('#cell-content').html(resp.note.noteContentHTML);
                window.history.pushState({ path: window.location.href }, resp.note.title, '/MyNotes/Note/' + resp.note.noteId);
                document.title = resp.note.title;
                $('*[data-noteId="'+resp.note.noteId+'"]').parent().addClass("active")

                e.preventDefault();
                test = false;
                return false;
            }
        }

    });
});

即使我已经声明e.preventDefault()要触发,javascript 将新内容加载到当前帧中而不刷新,但浏览器无论如何都会再次刷新。

我尝试过使用href="#",但是在这种情况下,当我回去处理它时,我总是得到两个相同的页面,一个没有,一个在末尾有 #,除此之外,它对用户不是很友好拥有所有链接href="#"

即使我告诉他不不不,我做错了什么让浏览器“正常”重定向?

我也尝试过添加onclick="javascript:void(0)"元素a,但没有帮助

标签: javascriptjqueryhtmlajax

解决方案


ajax是异步的。到调用成功回调时,事件已经在 DOM 树中冒泡并被处理。您需要preventDefault在发送请求之前致电。

$('.sidebar2 li a').click(function (e) {
    e.preventDefault(); // here for example
    test = true;
    var button = $(this);
    var noteId = button.data("noteid");

    $(".sidebar2 li.active").removeClass("active");
    var postData = { id: noteId };
    $.ajax({
        url: '/API/Note',
        type: 'get',
        data: postData,
        success: function (resp) {
            if (resp.success == true) {
                $('#app-bar-left').html(resp.note.navBarHTML);
                $('#cell-content').html(resp.note.noteContentHTML);
                window.history.pushState({ path: window.location.href }, resp.note.title, '/MyNotes/Note/' + resp.note.noteId);
                document.title = resp.note.title;
                $('*[data-noteId="'+resp.note.noteId+'"]').parent().addClass("active")


                test = false;
                // returning here makes no sense also
                // return false; 
            }
        }

    });
});

推荐阅读