我正在尝试制作一个简单的功能,但做错了。单击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();
});
答案 0 :(得分:1)
有错误
otherVar.detach()
因为otherVar
只是一个字符串,所以.detach()
不起作用,.detach()
接受jQuery对象。
所以正确的格式应该是
$(otherVar).detach();
答案 1 :(得分:0)
您将字符串作为所有这些参数传递
因此,调用detach()
或appendTo()
等方法会引发错误,因为字符串上不存在这些方法。
您需要传递jQuery对象。