JCr*_*ine 1 html javascript jquery html5
我正试图找到一个错误的底部我正在使用jQuery地图片段.这可以在jQuery 2下运行,但升级到3它会中断,我不知道为什么.卡住 :/
var menuItems = $("#topNav a");
var scrollItems = menuItems.map(function() {
var item = $($(this).attr("href")); // <= this is the culprit ??
if (item.length) {
return item;
}
});
// Expecting an object containing the page sections
console.log(scrollItems);Run Code Online (Sandbox Code Playgroud)
<!-- THIS FAILS (jQuery 3) -->
<script src="https://code.jquery.com/jquery-3.0.0.js"></script>
<!-- THIS WORKS HOWEVER (JQuery 2) -->
<!-- <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> -->
<!-- My navigation -->
<nav id="topNav">
<ul>
<li><a href="#">Home</a></li>
<li><a href="#about">About</a></li>
<li><a href="#services">Services</a></li>
<li><a href="#contact">Contact</a></li>
</ul>
</nav>
<-- My Page sections -->
<div id="page">
<div id="about">
<h2>About Us</h2>
</div>
<div id="services">
<h2>Services</h2>
</div>
<div id="contact">
<h2>Contact Us</h2>
</div>
</div>Run Code Online (Sandbox Code Playgroud)
问题是你的第一<a>要素.这具有href的#,这将导致$('#')其(相当正确地),使滋滋声选择器引擎抛出一个错误.为什么jQuery 2.x没有为此抛出异常是一个谜,因为它可能应该是.
要解决此问题,您可以从以下位置排除该值map():
var menuItems = $("#topNav a");
var scrollItems = menuItems.map(function() {
if ($(this).attr('href') == '#')
return null;
var item = $($(this).attr('href'));
if (item.length) {
return item;
}
}).get();
// Expecting an object containing the page sections
console.log(scrollItems);Run Code Online (Sandbox Code Playgroud)
<script src="https://code.jquery.com/jquery-3.0.0.js"></script>
<nav id="topNav">
<ul>
<li><a href="#">Home</a></li>
<li><a href="#about">About</a></li>
<li><a href="#services">Services</a></li>
<li><a href="#contact">Contact</a></li>
</ul>
</nav>
<div id="page">
<div id="about">
<h2>About Us</h2>
</div>
<div id="services">
<h2>Services</h2>
</div>
<div id="contact">
<h2>Contact Us</h2>
</div>
</div>Run Code Online (Sandbox Code Playgroud)