Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
351 views
in Technique[技术] by (71.8m points)

javascript - Href="#" Don't Scroll

I am pretty new to JS - so just wondering whether you know how to solve this problem.

Current I have in my code

<a href='#' class="closeLink">close</a>

Which runs some JS to close a box. The problem I have is that when the user clicks on the link - the href="#" takes the user to the top of page when this happens.

How to solve this so it doesn't do this ? i.e. I cant use someting like onclick="return false" as I imagine that will stop the JS from working ?

Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The usual way to do this is to return false from your javascript click handler. This will both prevent the event from bubbling up and cancel the normal action of the event. It's been my experience that this is typically the behavior you want.

jQuery example:

$('.closeLink').click( function() {
      ...do the close action...
      return false;
});

If you want to simply prevent the normal action you can, instead, simply use preventDefault.

$('.closeLink').click( function(e) {
     e.preventDefault();
     ... do the close action...
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...