Home >Web Front-end >JS Tutorial >Examples of using the toggle() function in jQuery_jquery
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"); });
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"); } );
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