开发者

Where to place 'return false;' in a jQuery function to correct page jumping issue

Initially I was looking for an answer to show/hide a page jumping issue. Having found an answer here: link with href="#" scrolls page to top when used with jquery slidetoggle, I need to understand where to put return false in the following code:

toggleDetail : function(obj) {
    $(obj).parent().parent().next().toggleClass('hide');
    $(obj).text() == 'Show' ? $(obj).text('Hide') : $(obj).text('Show');
},

and here's my call to the show/hide. The 'href="javascript开发者_运维百科:void(0);"' worked in stopping the page jumping, do I still need the 'return false'?

<a href="javascript:void(0);" onclick="VSASearch.toggleDetail(this)">Show</a>

I tried adding 'return false' to the end of each $(obj) line before the semi-colon, but that was not it.


You just need to return false on the onclick handler. If onclick returns false, then the postback/page reload will be stopped.

<a href="#" onclick="VSASearch.toggleDetail(this);return false;" />

Or you can return the result of your functions as follows:

toggleDetail : function(obj) {
    $(obj).parent().parent().next().toggleClass('hide');
    $(obj).text() == 'Show' ? $(obj).text('Hide') : $(obj).text('Show');
    return false;
},

with

<a href="#" onclick="return VSASearch.toggleDetail(this);" />


you want to return false from the onclick hander

<a onclick="VSASearch.toggleDetail(this); return false">Show</a>

Better yet, use unobtrusive javascript and assign event handler in the $() function:

<a id="show">Show</a>

....

$(function() {
 ....
 $("#show").click = function() {
     VSASearch.toggleDetail(this);
     return false;
 }


toggleDetail : function(obj) {
    $(obj).parent().parent().next().toggleClass('hide');
    $(obj).text() == 'Show' ? $(obj).text('Hide') : $(obj).text('Show');
    return false;
},
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜