日期:2014-05-16  浏览次数:20423 次

jQuery中的toggle()问题
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
<script src="jquery-1.9.0.js" type="text/javascript"></script>
<link href="css/default.css" type="text/css" rel="stylesheet" />

<script type="text/javascript">
$(function(){
//获得索引大于5的除了最后一条的项
var $category = $(".SubCategoryBox ul li:gt(5):not(:last)");

//隐藏部分索引
$category.hide();
var $btn=$(".showmore>a");
$btn.toggle(function(){
$category.show();
$(this).find("span").css("background","url(img/up.gif) no-repeat 0 0").text("精简显示品牌");
$(".SubCategoryBox ul li").filter(":contains('佳能'),:contains('尼康'),:contains('奥林巴斯')").addClass("promoted");
},function(){
$category.hide();
$("this").find("span").css("background","url(img/down.gif) no-repeat 0 0").text("显示全部品牌");
$(".SubCategoryBox ul li").removeClass("promoted");
})
})
</script>
</head>

<body>
<div class="SubCategoryBox">
    <ul>
    <li ><a href="#">佳能</a><i>(30440) </i></li>
    <li ><a href="#">索尼</a><i>(27220) </i></li>
    <li ><a href="#">三星</a><i>(20808) </i></li>
    <li ><a href="#">尼康</a><i>(17821) </i></li>
    <li ><a href="#">松下</a><i>(12289) </i></li>
    <li ><a href="#">卡西欧</a><i>(8242) </i></li>
    <li ><a href="#">富士</a><i>(14894) </i></li>
    <li ><a href="#">柯达</a><i>(9520) </i></li>
    <li ><a href="#">宾得</a><i>(2195) </i></li>
    <li ><a href="#">理光</a><i>(4114) </i></li>
    <li ><a href="#">奥林巴斯</a><i>(12205) </i></li>
    <li ><a href="#">明基</a><i>(1466) </i></li>
    <li ><a href="#">爱国者</a><i>(3091) </i></li>
    <li ><a href="#">其它品牌相机</a><i>(7275) </i></li>
    </ul>
    <div class="showmore">
    <a href="more.html"><span>显示全部品牌</span></a>
    </div>
    </div>
</body>
</html>


用toggle()函数运行结果与预期的不一样,预期的是这样的
,上面的按钮为什么不见了?在firebar上可以看到,按钮的display被自动设成了:display:none;为什么呢?如果用if-else判断就没有问题

------解决方案--------------------
那是因为你的$("this")用错了。
你代码里的$("this")指的是$(".SubCategoryBox ul li:gt(5):n