jQuery show/hide/toggle works, but doesn't stay as it should - it reverts to original state

核能气质少年 提交于 2019-12-04 11:07:31
peirix

I think there might be a problem with <a href="">... If you remove the href attribute (as it isn't needed anyway (if you want the appropriate cursor, use CSS)), it will work, at least it did for me.

As <a href=""> triggers an onClick event and refreshes the page, you can replace the blank href attribute with href="#" or href="javascript:void(0) to run the js event.

Another way of preventing the default following behaviour of a hyperlink is to use event.preventDefault():

Prevents the browser from executing the default action.

I would suggest this:

$('#question').click(function(e){
    e.preventDefault();
    $('div.showhide,#answer').toggle()
});

Well, when you click the link, the onClick event is triggered, and just after that, the page is reloaded, because the link points to the same page (href=""), and the browser follows the link.

When the page is reloaded, it reverts to its original state, hiding the answer.

To avoid this, you need to return false on the function triggered by the click event, so the browser won't follow the link.

To sum up, make your code look like this :

$('#question').click(function(){
    $('div.showhide,#answer').toggle();
      return false;
   });

Alternatively, you can make your link point to a javascript function. You would then remove the code above, replacing it with a standard javascript function :

function showAnswer()
{
    $('div.showhide,#answer').toggle();
}

and your link would become:

<a id="question" href="javascript:showAnswer();">

But keep in mind this is not recommended, as a client with javascript disabled will not be able to see the answers. You should always have a page working without javascript, and then add javascript to make it more usable.

usoban

What happens if you replace $('div.showhide,#answer').hide() with $('div.showhide,#answer').toggle();

Or even better, if you can, don't hide div in document.ready, instead use css display:none

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