我使用以下代码和Ethan Marcotte的书来检查浏览器是否支持某些DOM功能。
// Is this browser sufficiently modern to continue?
if ( !( "querySelector" in document
&& "addEventListener" in window
&& "getComputedStyle" in window) ) {
return;
}
window.document.documentElement.className += " enhanced";
var nav = document.querySelector( ".nav ul" ),
navToggle = document.querySelector( ".nav .skip" );
if ( navToggle ) {
navToggle.addEventListener( "click", function( e ) {
if ( nav.className == "open" ) {
nav.className = "";
} else {
nav.className = "open";
}
e.preventDefault();
}, false );
}
开发人员工具报告以下错误;
Uncaught SyntaxError:非法返回语句
我已尝试将返回值更改为false,但这并不起作用。基本上,如果找到这些DOM功能,它应该将增强类添加到html标记中。想知道是否有人可以在我出错的地方提供帮助。
感谢。
答案 0 :(得分:2)
我建议你在加载函数中插入所有代码:
window.onload = function () {
if (!("querySelector" in document
&& "addEventListener" in window
&& "getComputedStyle" in window)) {
return;
}
window.document.documentElement.className += " enhanced";
var nav = document.querySelector(".nav ul"),
navToggle = document.querySelector(".nav .skip");
if (navToggle) {
navToggle.addEventListener("click", function (e) {
if (nav.className == "open") {
nav.className = "close";
} else {
nav.className = "open";
}
e.preventDefault();
}, false);
}
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
<script src="http://code.jquery.com/jquery-1.12.1.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS" crossorigin="anonymous"></script>
<ul class="nav nav-pills nav-stacked">
<li class="active"><a href="#">Home</a></li>
<li class="dropdown">
<a class="skip dropdown-toggle" data-toggle="dropdown" href="#">Menu 1 <span class="caret"></span></a>
<ul class="dropdown-menu">
<li><a href="#">Submenu 1-1</a></li>
<li><a href="#">Submenu 1-2</a></li>
<li><a href="#">Submenu 1-3</a></li>
</ul>
</li>
<li><a href="#">Menu 2</a></li>
<li><a href="#">Menu 3</a></li>
</ul>