开发者

Need to bypass jquery toggle function

I need to be able to bypass the first function of a toggle and I was wondering how the jquery toggle works?

I understand that if I click on something, the first function is carried out and then when I click on it again, the second function is carried out.

What I need to be able to do is to bypass the first function and go directly to the second one.

Reason I am doing this is that the state of a button has been changed by another event that's happened. When I now click on that button for the first time, it assumes that it's the first time it's been clicked and will carry out the first function when I need it to carry out the second function.

Is there a way around this? If 开发者_开发知识库the jQuery toggle function equates to a true or false, then surely I should be able to check this and call on the correct script?

Many thanks!


I assume that the other event doesn't always fire before the first toggle, otherwise you could just reverse the functions.

Could you change your other event to fire the toggle? If the other event is performing the same task, then this would be the way to go.

  // From within the other event's handler
$(someselector).click();  // to fire the toggle

Otherwise, you could use .data() to place a flag on the element to check if the toggle() has fired yet. If it hasn't, then have the first function test to see if the element has been modified by the other event.

$(someselector).toggle(
    function() {
        var $th = $(this);
        if( !$th.data('toggled') ) {  // Check if toggle has not yet run
            $th.data('toggled', true);    // If not, set flag it to show it has run
            if( some_test_to_see_if_modified_externally ) {
                $th.click() // fire the second toggle
                return;     // return if element has been modified externally
            }
        } 
        // otherwise run the normal code  
    },
    function() {
        // your normal code
    }
);


You could create a variable outside of the toggle function: var isFirstToggle = true;.

Then in your toggle callback just return if it is equal to true;

var isFirstToggle = true;
$("#myId").toggle(function(){
   if (isFirstToggle === true){
      isFirstToggle = false;
      return;
}, function(){
   //do stuff on second toggle.
});

Let me know your thoughts and if this seems appropriate. There is probably cleaner ways to handle it, but this should work quick-n-dirty.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜