[英]Javascript / jQuery page change event on mobile browsers
我正在设计一个移动网站,牢记所有领先的浏览器 - Safari,Chrome,Dolphin,Opera。
我想在页面导航/更改/新页面请求时显示“加载”元素。
我不能在锚标签上使用click事件,因为存在许多与preventDefault();
。
我尝试了以下方法:
$(window).on('beforeunload', function() { ... });
但它在Dolphin或Opera中不起作用。
有人可以建议跨浏览器解决方案吗?
-
编辑 :我知道我不是很清楚地问我的问题,道歉。 我在这里创建了一个小提琴 - http://jsfiddle.net/hiteshpachpor/7dadA/5/基于响应。 该示例使用事件冒泡。
现在这是我面临的问题。 每次页面更改/导航时,我都会显示加载程序( $('.jacket').show();
)。 但我不希望它显示是否点击了链接; 我想在我的页面上做其他操作。 现在,添加$('.jacket').hide();
在所有这些行动中的行完全就足够了,但对于缩放原因来说它不是很理想。
这就是为什么我在评估'beforeunload'
方法,但没有运气,因为它不是跨浏览器兼容的。
有什么建议可以解决这个问题吗?
我认为你想要实现的是基本的AJAX请求? 但是你会以错误的方式去做。 您可以改为使用div加载请求的页面,然后设置ajax启动处理程序以显示加载消息。
你的页面标记看起来像
<nav>
<button data-url="homeURL">Home</button>
<button data-url="anotherURL">Other</button>
</nav>
<div id="loadhere"></div>
结果jquery将是这样的:
//on button click
$('nav button').click(function(){
//set the url
url = $(this).attr('data-url');
//load the page
$('#loadhere').load(url);
});
//ajax start handler
$(document).ajaxStart(function(){
$('#loadhere').text('LOADING');
});
这是一个示例代码
希望这可以帮助
你可以在body元素中有一个onLoad函数调用一个加载div来显示,然后setTimeout让我们说3秒然后隐藏加载div并显示所有其他div /其余的body
编辑:我很确定这适用于所有浏览器。 一旦我上电脑(现在在我的手机上),我会附上一个代码片段;)
正如评论中提到的那样。 但是我更喜欢事件委托而不是在整个dom附加事件。
// this is your original eventListener which prevents the default action (aka, navigating away)
$('#random-link').click(function(event){
event.preventDefault();
$('#result').text('I was clicked from random-link event.')
});
// this would be the delegated listener. It wouldn't have to be all "a" tags
// that you respond to. It could be any css selector that causes the
// loading message that you want.
$(window).on('click', 'a', function() {
alert('I still bubble up.');
});
更新:
也许你不应该为“链接”触发$('.jacket').show()
。
$('.jacket').hide();
$('a:not(.prevent)').click(function() {
$('.jacket').show();
});
$('.prevent').click(function(event) {
event.preventDefault();
$('.jacket').hide();
});
有一个jquery移动小部件。 这使用到版本1.4
$.mobile.loading( "show", { //show loading image
text: "Your request is processing. please wait ...",
textVisible: true,
theme: "b",
textonly: false,
});
为了回应您的编辑:
您可以使用event.isDefaultPrevented()
。
$(function() {
$('.jacket').hide();
$('.prevent').click(function(event) {
event.preventDefault();
});
$('a').click(function(event) {
if (!event.isDefaultPrevented())
$('.jacket').show();
});
});
JSFiddle: http : //jsfiddle.net/F4uPx/
警告:确保在其他事件处理程序之后分配$('a').click()
事件处理程序; 否则它将首先执行并将失败,因为preventDefault()
将不会被解雇。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.