代码之家  ›  专栏  ›  技术社区  ›  DethoRhyne

e、 链接上的preventDefault()仍会加载页面

  •  0
  • DethoRhyne  · 技术社区  · 6 年前

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

    我正在创建一个自定义处理程序,以便在按下新内容时网站不会刷新(例如,类似于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 元素,但这没有帮助

    1 回复  |  直到 6 年前
        1
  •  3
  •   Yury Tarabanko    6 年前

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