JavaScript设备检测几乎完成,但Google Chrome出现1个错误';s错误控制台
我正在编写一个设备和功能检测库(不是真正用于任何实际用途,只是试验和玩),至于设备检测,我应该完成,但我只有一个(我认为)问题。我的代码:JavaScript设备检测几乎完成,但Google Chrome出现1个错误';s错误控制台,javascript,device,detection,user-agent,Javascript,Device,Detection,User Agent,我正在编写一个设备和功能检测库(不是真正用于任何实际用途,只是试验和玩),至于设备检测,我应该完成,但我只有一个(我认为)问题。我的代码: var $device = { mobile: { android: navigator.userAgent.match(/Android/i), blackberry: navigator.userAgent.match(/BlackBerry/i), iphone: navigator.userA
var $device = {
mobile: {
android: navigator.userAgent.match(/Android/i),
blackberry: navigator.userAgent.match(/BlackBerry/i),
iphone: navigator.userAgent.match(/iPhone/i),
ipod: navigator.userAgent.match(/iPod/i),
opera: navigator.userAgent.match(/Opera Mini/i),
windows: navigator.userAgent.match(/(Windows Phone OS|Windows CE|Windows Mobile|IEMobile)/i)
},
tablet: {
ipad: navigator.userAgent.match(/iPad/i),
galaxy_tab: navigator.userAgent.match(/(GT-P1000|GT-P1000R|GT-P1000M|SGH-T849|SHW-M180S)/i),
windows: navigator.userAgent.match(/Tablet PC/i)
},
desktop: {
other: navigator.userAgent.match(/(Linux|X11)/i),
mac: navigator.userAgent.match(/(Macintosh|Mac OS X)/i),
windows: navigator.userAgent.match(/Windows/i)
}
}
$device = {
mobile: {
any: $device.mobile.android || $device.mobile.blackberry || $device.mobile.iphone || $device.mobile.ipod || $device.mobile.opera || $device.mobile.windows
},
tablet: {
any: $device.tablet.ipad || $device.tablet.galaxy_tab || $device.tablet.windows
},
desktop: {
any: $device.desktop.other || $device.desktop.mac || $device.desktop.windows
}
}
if($device.mobile.any) {
$device = {
type: "Mobile Phone"
}
} else if($device.tablet.any) {
$device = {
type: "Tablet"
}
} else if($device.desktop.any) {
$device = {
type: "Desktop"
}
}
if($device.desktop.windows){alert("Hello")}
现在,就userAgent字符串而言,我并不完全相信它们都是正确的,我还没有测试它们,但是这不是我的问题。我的问题是,它不会发出警告,谷歌chrome开发工具中的错误信息是:uncaughttypeerror:无法读取未定义的属性“windows”
现在,根据我使用谷歌工具的经验,这告诉我,在某些地方我的语法是错误的,而不是我的方法,但我似乎无法得到它。有什么帮助吗?(顺便说一句:我知道用户代理嗅探是不好的,这就是为什么我稍后也会用功能检测来支持它。)您经常重新分配
$device
,将它以前拥有的功能一扫而光。当脚本到达底部时,$device.desktop.windows
不再存在,因为此时,$device
将只具有类型
,而没有其他属性
不要每次都重新分配设备,而是添加以下内容:
var $device = {
mobile: {
...
}
};
...
$device.mobile.any = $device.mobile.android || $device.mobile.blackberry || ... ;
正如Matt所说,但也不是替换
$device
对象:
> if($device.mobile.any) {
> $device = {
> type: "Mobile Phone"
> }
您只需添加一个属性和值:
if($device.mobile.any) {
$device.type = "Mobile Phone";
}
在任何情况下,您可能会发现最好使用解析字符串的。当然,对于新的和罕见的浏览器来说,它并不完全准确,而且容易出错,但它可能会起到作用。ooh,我认为您只能通过执行整个代码块来分配另一个属性(例如mobile.any)。谢谢成功了!