我正在使用ajax调用刷新网页内的div。但有时页面在 Chrome 中滚动到顶部。
我认为这是同样的问题:How do I stop a web page from scrolling to the top when a link is clicked that triggers JavaScript?
但是设置return false
并没有解决我的问题。我的代码:
<span class="current" id="tab-kisiler"><a class="peoples" onclick="Refresh(); return false;">Refresh</a></span>
function Refresh() {
$.post('socket/get_online_users', {city: city}, function (data) {
$('#random_users').html(data);
});
}
如何解决这个问题?
最佳答案
试试这个
$(function() {
$(".peoples").on("click",function(e) {
e.preventDefault();
$.post('socket/get_online_users', {city: $(this).data("city") }, function (data) {
$('#random_users').html(data);
});
});
});
使用
<span class="current" id="tab-kisiler"><a class="peoples" data-city="Chicago">Refresh</a></span>
并假设 .current 或 #tab-kisiler 上没有事件处理程序
此外,当数据加载到 random_users 中时,页面可能会移动
要阻止双击造成困惑,请尝试以下操作(未测试):
$(function() {
$(".peoples").on("click",function(e) {
e.preventDefault();
if ($(this).data("active")) return;
$(this).data("active",true);
$.post('socket/get_online_users', {city: $(this).data("city") }, function (data) {
$('#random_users').html(data);
$(this).data("active",false);
});
});
});
关于javascript - Ajax请求在chrome中滚动到顶部,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33633638/