javascript className函数存在问题

Issues with javascript className function

本文关键字:问题 存在 函数 className javascript      更新时间:2024-05-18

我正在构建一个android应用程序,该应用程序使用现有移动web应用程序的web视图。现有的移动web应用程序有一个页眉图形和一个使用无序列表的页脚导航。

由于android应用程序具有本地导航功能,并且应用程序中已经内置了页眉,因此当在移动web应用程序中使用页面的web视图时,android应用程序中的web应用程序页眉和页脚是多余的。由于移动网络应用程序将用于黑莓和windows手机等设备,我无法普遍删除页眉和页脚。此外,网络应用程序的标题使用了一些CSS,所以我需要确保它在移动网络应用程序中。

所以我决定尝试使用javascript来检测android操作系统,当它检测到android操作系统时,动态地为页眉和页脚div分配一个类名,并在CSS中引用类名以不显示这些div。如果操作系统不是android,那么它将创建指向移动web应用程序中标头所需的CSS文件的样式指针。

我不是javascript或CSS专家,所以我想出了一个简单的测试来确保这一切都有效。一切都正常,只是它似乎没有将类名分配给div,以便在检测到android操作系统时不显示它。我知道它正在检测android操作系统,因为我在if语句中有一个警报,这很有效。我不知道哪里出了问题。我在使用android 4.4和Chrome的谷歌Nexus 7和使用Chrome的摩托罗拉RAZR Droid上测试了这一点。

测试代码如下:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<style>
.android
{
    display:none;
}
</style>
<script language="javascript" type="text/javascript">
var isMobile = {
    Android: function() {
        return navigator.userAgent.match(/Android/i);
    }
};
var divID = "test";
var newClassName = "android";
function changeClass() {
var divReference = document.getElementById(divID);
divReference.className = newClassName;
};
if( isMobile.Android() ) 
    {
        alert("android!");
        changeClass();
}
else
{
    alert("Not android!");
    document.write("<link rel='stylesheet' href='header.css' type='text/css'>");
}
</script>


<title>Untitled Document</title>
</head>
<body>
<h1>Detect android device and hide second UL list below. If not android device, then hide   the first UL list.</h1>
<div class="notandroid">
<ul>
<li>One</li>
<li>two</li>
<li>three</li>
</ul>
</div>
<h2>This header is after the first UL list</h2>
<div id="test">
<ul>
<li>four</li>
<li>five</li>
<li>six</li>
</ul>
</div>
<h2>This header is after the second UL list</h2>
</body>
</html>

尝试将脚本标记放在正文的底部。在运行脚本时,div不存在。浏览器一遇到javascript就在脚本标记中解析并运行它,因此您需要在DOM准备好后运行javascript。

在定义要用于document.getElementById()的Element之前,您正在调用changeClass()。要么将代码放在onload = function(){/*in here*/}中,要么将脚本标记放在身体底部。简而言之,在使用JavaScript获取HTML之前,必须先创建HTML。此外,XHTML中不支持document.write()。http://www.w3.org/MarkUp/2004/xhtml-faq#docwrite

避免浏览器检测有很多充分的理由。但是,如果你决心继续这样做,你面临的主要问题是,这个代码正在HEAD中运行,但你要寻找的DIV还不存在,因为它在主体中。如果您想要HEAD中CSS的document.write,您可能需要在两个块中完成此操作。