jQuery Show/Hide Question

北战南征 提交于 2019-12-20 03:40:29

问题


I'm just trying to preform a very simple jQuery action.

I have two components: #safety and #safety-tab a, the #safety needs to be hidden on load. When the a link in the #safety-tab is clicked, it will hide itself and slideUp the #safety.

This sort of works, but the #safety box just flickers on click, doesn't stay shown:

 $(document).ready(function() {
   $("#safety-tab a").click(function() {
     $(this).hide();
     $("#safety").removeClass("hide");  
   });
   });

While the markup is this:

     <div id="safety" class="hide group">
      ...
     </div><!--end #safety-->
    <div id="safety-tab">
      <a href="">...</a>
    </div><!--end #safety-tab-->

Any idea what I'm doing wrong?


回答1:


Add return false; or event.preventDefault() to your click handler.

$(document).ready(function() {
   $("#safety-tab a").click(function( event ) {
     $(this).hide();
     $("#safety").removeClass("hide");  
     event.preventDefault();
   });
});

This prevents the default behavior of the <a> element, which is reloading the page.

  • http://api.jquery.com/event.preventDefault

Using event.preventDefault() will preserve event bubbling which is sometimes needed.

Doing return false; will prevent the default behavior, but it will also halt the bubbling.




回答2:


try return false as you are clicking on a link;

 $(document).ready(function() {
   $("#safety-tab a").click(function() {
     $(this).hide();
     $("#safety").removeClass("hide");  
     return false;
   });
   });


来源:https://stackoverflow.com/questions/3401662/jquery-show-hide-question

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!