Home > Web Front-end > JS Tutorial > body text

Examples of using the toggle() function in jQuery_jquery

WBOY
Release: 2016-05-16 16:03:29
Original
1221 people have browsed it

I encountered an interesting example today and recorded it.

A first-level menu has a second-level menu inside. The second-level menu links page elements through anchor points. The desired effect is that when the anchor is clicked, the page links to the corresponding anchor, and the second-level menu is hidden. When the first-level menu is clicked again, execution continues. .

I tried many methods but it didn’t work. Finally, I realized it by reading jquery’s toggle function.

    //这样写可以
    $(".nav").toggle(function(){
      $(".content").slideToggle();
    });
    //这样写不可以
    $(".nav").toggle(function(){
     $(".content").slideDown();
   },function(){
     $(".content").slideUp();
   });
   //这样写也可以
    $(".nav").click(function(){
      $(".content").toggle("slow");
    });

Copy after login

Attached are the instructions for using toggle()

toggle(fn,fn)

Switch the function to be called on each click.
If a matching element is clicked, the first function specified is triggered, and when the same element is clicked again, the second function specified is triggered. Each subsequent click repeats the call to these two functions in turn.

Can be deleted using unbind("click").

Return value
jQuery

Parameters

fn (Function): The function to be executed when the odd-numbered click is made.

fn (Function): The function to be executed when the even-numbered click is made.

Example

Switch a class to the table

jQuery code:

$("td").toggle( 
function () { 
$(this).addClass("selected"); 
}, 
function () { 
$(this).removeClass("selected"); 
} 
);

Copy after login

Additional: toggle only works when clicked, hover is just an event when the mouse moves in and out, and has nothing to do with clicks. Both can be used together

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template