获取浏览器信息
来源:5-1 navigator对象及属性(userAgent)
zz胖胖
2017-04-06 16:33:23
请问一下我的代码哪里出现了错误?望指出,非常感谢。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>userAgent</title>
</head>
<body>
<input type="button" value="点击获取浏览器信息" id="ab">
<script type="text/javascript">
var ab=document.getElementById("ab");
ab.onclick=function getbrowser(){
var explorer=navigator.userAgent.toLowerCase(),
browser;
if(explorer.indexOf("msie")>-1){
browser="IE";
}else if(explorer.indexOf("firefox")>-1){
browser="火狐";
}else if(explorer.indexOf("safari")>-1){
browser="Safari";
}else if(explorer.indexOf("chrome")>-1){
browser="谷歌";
}return browser;
}
var explorer=getbrowser();
document.write('<br>'+'您使用的浏览器是'+explorer+'浏览器')//补充代码
</script>
</body>
</html>
2回答
<input type="button" value="点击获取浏览器信息" id="ab"> <script type="text/javascript"> var ab=document.getElementById("ab"); ab.onclick=function(){ var explorer=navigator.userAgent.toLowerCase(), browser = ""; if(explorer.indexOf("msie")>-1){ browser="IE"; }else if(explorer.indexOf("firefox")>-1){ browser="火狐"; }else if(explorer.indexOf("safari")>-1){ browser="Safari"; }else if(explorer.indexOf("chrome")>-1){ browser="谷歌"; } document.write('<br>'+'您使用的浏览器是'+browser+'浏览器'); } </script>
ziom
2017-04-06
你是要按按钮显示浏览器还是打开页面就直接显示浏览器,看你这个代码前后有点矛盾,如果是要实现前者,那么需要把document.write(...)这句放到按钮的onlick事件函数内,并且是不需要给function命名的,也不需要返回值。
如果是后者,改法最简单,直接把"ab.onclick="删去,也即定义了一个gerbrowser()函数,会返回浏览器名称,然后用var explorer接收并输出到页面
相似问题