我正在尝试制作一个简单的功能但做错了什么。点击href会导致页面跳转,功能失败。小提琴:http: //jsfiddle.net/XkzUK/5/
HTML:
<nav>
<ul id="site-nav">
<li class="nav1"><a href="#recent">Recent</a></li>
<li class="nav2"><a href="#highlights">Highlights</a></li>
<li class="nav3"><a href="#animals">Animals</a></li>
<li class="nav4"><a href="#cars">Cars</a></li>
</ul>
</nav>
<div id="content-listing">
<div id="recent">
<ul class="top-level">
</ul>
</div>
<!--end recent-->
<div id="highlights">
<ul class="top-level">
</ul>
</div>
<!--end highlights-->
<div id="animals">
<ul class="top-level">
</ul>
</div>
<!--end animals-->
<div id="cars">
<ul class="top-level">
</ul>
</div>
<!--end cars-->
</div>
<!--end content-listing-->
JS:
var test1;
var test2;
var test3;
var test4;
function switcher(divToShow, thisVar, otherVar, ajaxContent) {
$("#site-nav li a").parents().removeClass("nav-active");
$(this).addClass("nav-active");
if(otherVar) {
otherVar.detach();
}
if(typeof thisVar === 'undefined') {
thisVar = $(divToShow + "ul.top-level").load('/echo/html/', {
html: ajaxContent
}, function () {
alert("I'm new");
});
} else {
thisVar.appendTo("#content-listing");
alert("I'm old");
}
}
//Recent
$("#site-nav .nav1").on("click", function (event) {
switcher("#recent", "test1", "test2", "<li>1</li> <li>2</li> <li>3</li>");
event.preventDefault();
});
//Highlights
$("#site-nav .nav2").on("click", function (event) {
switcher("#recent", "test2", "test1", "<li>A</li> <li>B</li> <li>C</li>");
event.preventDefault();
});