简体   繁体   中英

jQuery: How do I trigger .slideToggle() on links?

How do I perform a jQuery 'slidetoggle' effect using a hyperlink, instead of an input button, as the action item?

At the jQuery reference page

It only gives an example of using a form input button.

I would like to have instead of a button, a hyperlink to be the toggle clickable action.

$("#anch").click(function () {
      $("#para1").slideToggle("slow");
    });



<a id='anch'>Toggle</a>
  <p id='para1'>
    This is the paragraph to end all paragraphs.  You
    should feel <em>lucky</em> to have seen such a paragraph in
    your life.  Congratulations!
  </p>

If you have a link like so:

<a id="toggleLink" href="#">CLICK ME!</a>

Just use the following function to slideToggle your div

 $("#toggleLink").click(function () {
      $("#myDiv").slideToggle("slow");
    });

In addition to the other answers, if your hyperlink has an href attribute (which it should, so it will be displayed as a link), you may want to neutralize it by returning false on your event handler (if you don't, the page will scroll up when you click on the link):

$('a').click(function(){
    $('p').slideToggle();
    return false;
});

Other than that, there shouldn't be any difference between a button and an hyperlink. While you're reading the documentation, you'd be wise to start with jQuery's Selectors .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM