javascript - 链接上的 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
,但没有帮助
解决方案
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;
}
}
});
});
推荐阅读
- angular - Angular Universal - 在服务器端获取当前 url
- .net - 在cshtml文件中连接字符串
- kubernetes - 如何使用 kubectl 从单个 yml 文件中的多个模板运行特定模板
- python - ValueError:形状 (None, 0, 5) 和 (None, 5) 不兼容
- email - Spring Integration Email outbound gateway:如何将内容编码设置为 UTF-8?
- reactjs - Redux:for循环在reducer中工作,但过滤器没有
- flutter - 元素数据不刷新
- deep-learning - 如果我们主要使用 LSTMs 而不是 RNNs 来解决梯度消失问题,为什么我们不能只使用带有 RNNs 的 ReLUs/leaky ReLUs 呢?
- c++ - 如何在类方法中使用 gcc 选项 --wrap=symbol
- react-native - 我已经安装了@react-navigation/stack,但出现错误:错误:无法从 `App.js` 解析模块`@react-navigation/stack`: