Cancel Browser Scroll Reset for Inline Onclick

2019-07-31 11:12发布

问题:

I'm using prototype to construct an ajax request from an inline onclick on a link. The function shows an element on the page and this all works fine, except that the browser scroll bar resets to the top after every click of the link. This is bad b/c sometimes the content that I want to show is partially scrolled down the page and this makes it so the user cannot see it. I realize it's better to not include the onclick inline, but I have a situation where I dynamically create these links and then cache the html so it is faster this way. Is there any way to cancel this browser scroll reset using an inline onclick? This is what my code looks like:

<a href="#" rel="nofollow" onclick="linkAjax('example')" id="word_link_example">example</a>

function linkAjax(word){ 
  if(!making_ajax_request){
    making_ajax_request = true;
    new Ajax.Request('/example/test',
     {parameters:{data: word},  
      onLoading: function(){searchLoading();},  
      onComplete: function(){
        making_ajax_request = false;
      }
    });
  } else { }
}

回答1:

Your onclick needs to return false to stop the browser from reloading the page (resulting in scrolling to the top). Try:

<a href="#" rel="nofollow" onclick="linkAjax('example'); return false;" id="word_link_example">example</a>


回答2:

Do this: onclick="linkAjax('example') return false"