0

我有以下代码,它向下滑动,但没有向上滑动。请你能帮我找出错误,如果可能有更好的方法来做到这一点,我试过slideToggle,但这不能检查元素的状态,因为你可以在哪里使用隐藏和显示检查$('#my_div').is(':hidden')

这是我的代码:

$("a.advanced_search_toggle").click(function() { 
    if ($("#advanced_search_box").hasClass('closed')) {
        $("#advanced_search_box").slideDown(function(){
            $("a.advanced_search_toggle").text('Simple Search');
            $("a.advanced_search_toggle").removeClass('down_arrow');
            $("a.advanced_search_toggle").addClass('up_arrow')
            $("a.advanced_search_toggle").removeClass('closed');
            $("a.advanced_search_toggle").addClass('open'); 
        });
    } else {
        $("#advanced_search_box").slideUp(function(){
            $("a.advanced_search_toggle").text('Advanced Search');
            $("a.advanced_search_toggle").removeClass('up_arrow');
            $("a.advanced_search_toggle").addClass('down_arrow');
            $("a.advanced_search_toggle").removeClass('open');
            $("a.advanced_search_toggle").addClass('closed');                       
        });         
    }
    return false;
}); 

请注意,默认情况下,我添加了一个封闭类#advanced_search_box

4

2 回答 2

1

您需要将 .removeClass 调用更改为“#advanced_search_box”而不是“a.advanced_search_toggle”。它不会删除您正在检查的元素上的类名,因此不会向上滑动,只会向下滑动。

$("a.advanced_search_toggle").click(function() { 
    if ($("#advanced_search_box").hasClass('closed')) {
        $("#advanced_search_box").slideDown(function(){
            $("a.advanced_search_toggle").text('Simple Search');
            $("a.advanced_search_toggle").removeClass('down_arrow');
            $("a.advanced_search_toggle").addClass('up_arrow')
            $(this).removeClass('closed');
            $(this).addClass('open'); 
        });
    } else {
        $("#advanced_search_box").slideUp(function(){
            $("a.advanced_search_toggle").text('Advanced Search');
            $("a.advanced_search_toggle").removeClass('up_arrow');
            $("a.advanced_search_toggle").addClass('down_arrow');
            $(this).removeClass('open');
            $(this).addClass('closed');                       
        });         
    }
    return false;
});
于 2012-07-08T17:47:20.267 回答
0

您正在尝试修改链接而不是元素的属性。此外,通过将对象分配给变量来缓存对象,这有助于更简单的引用和优化。尝试以下操作:

$("a.advanced_search_toggle").click(function() {
    var link = $(this);
    var box = $("#advanced_search_box");
    if (box.hasClass('closed')) {
        box.slideDown(function(){
            link.text('Simple Search').removeClass('down_arrow').addClass('up_arrow');
            box.removeClass('closed').addClass('open');
        });
    } else {
        box.slideUp(function(){
            link.text('Advanced Search').removeClass('up_arrow').addClass('down_arrow');
            box.removeClass('open').addClass('closed');                    
        });         
    }
    return false;
});

演示:http: //jsfiddle.net/m9XMn/

于 2012-07-08T17:56:43.500 回答