Stop javascript onclick 'page jumping'

家住魔仙堡 提交于 2019-12-05 07:48:29

问题


Can't seem to prevent the jump to top of page behavior.

I've tried everything suggested here preventing onclick page jumps

What else could be done to stop onclick page jumps?

Thanks.

Here's a snippet of the HTML and JS

HTML:

<a href="javascript: return null;" onclick='javascript:getPosts("page=1&display=all"); return false;'>Everyone</a>


JS:

function getPosts(qry) {
    var thePage = 'posts.php?' + qry;
    myReq.open("GET", thePage, true);
    myReq.onreadystatechange = theHTTPResponse;
    myReq.send(null);
}

function theHTTPResponse() {
    if (myReq.readyState == 4) {
        if(myReq.status == 200){
            var response = myReq.responseText;
            document.getElementById('posts').innerHTML = response;
        }
    } else {
        document.getElementById('posts').innerHTML = '<img src="images/ajax-loader.gif" />';
    }
}

回答1:


Returning false in the onclick is really the way to go. If that's not working for you, we need to see code.




回答2:


As far as I know, the events are already JS so, you dont need to put onclick="javascript:...". Try this:

<a href="javascript: return null;" onclick='getPosts("page=1&display=all"); return false;'>Everyone</a>



回答3:


href="javascript:void(0);"




回答4:


<a href="javascript:;" onclick="...">Everyone</a>

Note the semicolon.




回答5:


this is what i use and it works

<a href="javascript:getPosts('page=1&display=all'); return false;">Everyone</a>

When it comes to ajax requests using the function that is tied to the 'onClick' event as the href always solves the page jumping problem for me.




回答6:


all you need is

<a href="javascript:">My Link!</a>

and add whatever other attributes you need to the tag.




回答7:


I've always used:

<a href=""></a>

Mostly because I hate that using

<a href="#"></a>

appends a # to the end of the url.

Edit:

Are you sure it isn't a browser specific problem or preference?




回答8:


Strangely, the problem was corrected after I deleted the contents of my php script, saved, then reinserted the same content. Not sure what effect this had but seems to fix the jumping.

I guess the issue was never with returning false in onclick.

Thanks for everyone's time!




回答9:


href="javascript:undefined" should do the trick



来源:https://stackoverflow.com/questions/1924031/stop-javascript-onclick-page-jumping

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