我不明白为什么我的代码没有按顺序运行......下面的代码不会执行document.write部分,但是它会在它完好后执行部分。我认为它与时间有关,让浏览器执行。我尝试在某些部分使用setTimeout,但它不能正常工作,或者我做错了。
function isBrowserMobile()
{
var iPadAgent = navigator.userAgent.match(/iPad/i) != null;
var iPodAgent = navigator.userAgent.match(/iPhone/i) != null;
var AndroidAgent = navigator.userAgent.match(/Android/i) != null;
var webOSAgent = navigator.userAgent.match(/webOS/i) != null;
if (iPadAgent || iPodAgent || AndroidAgent || webOSAgent)
{
document.write("<body bgcolor='Orange'><b>Mobile browser detected!</b></body>");
var choice = confirm("Do you want to visit the mobile site?")
if (choice)
mobile();
else
desktop();
}
}
答案 0 :(得分:1)
修改强>
我建议您不要使用document.write
,而是使用DOM,如下所示:
document.body.style.backgroundColor='Orange';
document.body.innerHTML='This is a text';
在桌面浏览器中测试代码时,可以将true ||
添加到if条件的开头。
我的原始答案使用的是不是标准的
的innerText答案 1 :(得分:0)
浏览器很少在函数完成处理之前更新页面。因此document.write
已被执行,但在函数完成之前可能不会显示结果。
正如minitech所说,无论如何,这是一个非常垃圾的功能。您应该根据屏幕尺寸询问,而不是UA嗅探。
请注意,如果在文档加载完成后运行该函数,则对document.write
的调用将清除文档的全部内容,包括脚本。