开发者

simple toggle problem

I'm just programming a little function that toggles a content by fading it in and out.

this.advancedSearch = function(fieldset, trigger开发者_JS百科Btn){
    fieldset.hide()
    triggerBtn.click(function(){
        fieldset.toggle(function(){ $(this).stop(false, true).fadeIn(300) }, function(){ $(this).stop(false, true).fadeOut(300) });
        return false;
    })
}

if just I use toggle() it works, but when i insert the two functions nothing happens and no error is thrown. Is there something i have done wrong?


I assume that you intend the triggerBtn to fire the toggle event on fieldset.

If so, try this:

this.advancedSearch = function(fieldset, triggerBtn){
    fieldset.hide();
    triggerBtn.click(function(){
        fieldset.click();
    });
    fieldset.toggle(function(){ $(this).stop(false, true).fadeIn(300) }, 
                    function(){ $(this).stop(false, true).fadeOut(300) })
}

The way you had it, every time you clicked on triggerBtn, you were assigning the toggle event handler to the fieldset.


EDIT:

Alternatively, if you don't need the click (toggle) event on fieldset at all, then David's answer would work.


You want the toggle event to be attached to the object being clicked:

this.advancedSearch = function(fieldset, triggerBtn) {
    fieldset.hide()
    triggerBtn.toggle(
        function(){ fieldset.stop(false, true).fadeIn(300) }, 
        function(){ fieldset.stop(false, true).fadeOut(300) }
    );        
}


toggle function binds a click event on the element that toggles the element automatically.. so calling toggle inside your button click callback doesnt toggle the element, it simply binds an event. Its much simpler to implement this by hand rather than using toggle.

this.advancedSearch = function(fieldset, triggerBtn){
    fieldset.hide()
    triggerBtn.click(function(){
        if(fieldset.hasClass('toggle-on')) {
            fieldset
                .removeClass('toggle-on')
                .stop(false, true).fadeOut(300);
        }
        else {
            fieldset
                .addClass('toggle-on')
                .stop(false, true).fadeIn(300);
        }
        return false;    
    })
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜