A usage instance of the toggle of function in jQuery

  • 2020-05-30 19:25:06
  • OfStack

I came across an interesting example today. Write it down.

There are 1 level 1 menu, 1 level 2 menu inside, and 2 level menu links the page elements through the anchor points. Want to achieve the effect is when click the anchor point, the page links to the corresponding anchor point, while the level 2 menu hidden, and then click the level 1 menu, continue to execute.

Many of them failed, but they were finally implemented by reading jquery's toggle function.

    // I could write it this way 
    // You can't write it like that 
   // I could have written it this way 

Instructions for the use of toggle() are also attached


Switch the function you want to call each time you click.
If a matching element is clicked, the specified first function is fired, and when the same element is clicked again, the specified second function is fired. Each subsequent click repeats the alternate calls to the two functions.

You can use unbind("click") to delete.

The return value


fn (Function) : function to execute on the oddth click.

fn (Function) : function to execute on the eventh click.

The sample

Toggle 1 class to the table

jQuery code:

function () { 
function () { 

Addition: toggle works only when you click, hover is just a mouse in and out event, which has nothing to do with clicking. Two can be used with one

Related articles: