<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判断就没有问题

解决方案 »

  1.   

    那是因为你的$("this")用错了。
    你代码里的$("this")指的是$(".SubCategoryBox ul li:gt(5):not(:last)");
    改成$(".showmore")就可以了。
    demo: http://jsfiddle.net/a5NYA/
      

  2.   

    不是这个问题吧,this指的是单击它的那个元素,这里应该指的是.showmore>a啊,而且,在你给的代码里,就写this也是对的,为什么在我的电脑上就不行
      

  3.   

    jquery 1.9里面已经删除了toggle(fn1, fn2)这个函数:详见
    http://api.jquery.com/toggle-event/
      

  4.   

    你引用版本低一点的jquery就可以了
    query 1.9里面已经删除了toggle(fn1, fn2)这个函数:
    引用
    Note: This method signature was deprecated in jQuery 1.8 and removed in jQuery 
    1.9. jQuery also provides an animation method named .toggle() that toggles the 
    visibility of elements. Whether the animation or the event method is fired depends on 
    the set of arguments passed.