jquery click on anchor element forces scroll to top?

后端 未结 8 1599
故里飘歌
故里飘歌 2020-12-28 08:07

jQuery hyperlinks - href value? text][1]

I am running in to a problem using jquery and a click event attached to an anchor element. [1]: jQuery hyperlinks - href

8条回答
  •  臣服心动
    2020-12-28 08:42

    This question is more of a debugging exercise since it's stated that you are using the correct functions from the jQuery Event object.

    In a jQuery event handler, you can do either, or both, of two basic things:

    1. Prevent the default behavior of the element (The A HREF="#", in your case):

    jQuery("#id_of_anchor").click(function(evt) { 
      // ...
      evt.preventDefault(); // assuming your handler has "evt" as the first parameter
      return false;
    }
    

    2. Stop the event from propagating to event handlers on the surrounding HTML elements:

    jQuery("#id_of_anchor").click(function(evt) { 
      // ...
      evt.stopPropagation(); // assuming your handler has "evt" as the first parameter
    }
    

    Since you're not getting the expected behavior, you should take out the ajax call temporarily, replace it with some innocuous code like setting a form value, or -shudder- alert("OK") and test if you still scroll to the top.

提交回复
热议问题