1. ホーム
  2. javascript

[解決済み] preventDefault() on an <a> tag

2022-04-30 04:47:07

Question

I have some HTML and jQuery that slides a div up and down to show or hide` it when a link is clicked:

<ul class="product-info">
  <li>
    <a href="#">YOU CLICK THIS TO SHOW/HIDE</a>
    <div class="toggle">
      <p>CONTENT TO SHOW/HIDE</p>
    </div>
  </li>
</ul>

$('div.toggle').hide();
$('ul.product-info li a').click(function(event){
  $(this).next('div').slideToggle(200);
}

My question is: How do I use preventDefault() to stop the link acting as a link and adding "#" to the end of my URL & jumping to the top of the page?

I can't figure out the right syntax, I just keep getting an error saying

preventDefault() is not a function.

How to solved?

Try something like:

$('div.toggle').hide();
$('ul.product-info li a').click(function(event) {
    event.preventDefault();
    $(this).next('div').slideToggle(200);
});

のそれに関するページはこちらです。 jQueryドキュメント