开发者

In Firefox, double-clicking on a tag with href set to # but with onclick set to go to another page will effectively make us remain on the current page

开发者 https://www.devze.com 2022-12-20 11:56 出处:网络
Suppose we have the ff. in a.html: <script> function onClick() { // Do some important stuff and then...

Suppose we have the ff. in a.html:

<script>
  function onClick() {
    // Do some important stuff and then...
    location = "b.html";
  }
</script>
<a hre开发者_Python百科f="#" onclick="onClick();">Link</a>

Double-clicking on Link will trigger the event-handler onClick. However, the second click in the double-click seems to be interpreted as another click and causes the page to jump to the named anchor. In effect, the location isn't changed.

My questions are:

  1. Is this a browser bug or feature?

  2. Is there a way to work-around this behavior?


You could try

href="javascript:void(0);"

instead


Use window.location = "b.html". location by itself has no special meaning.

The anchor jumping is unrelated. You can disable it by stopping the event.

function onClick(event) {
  event.preventDefault();
  event.stopPropagation();
}

<a href="#" onclick="onClick(event)">Link</a>


gshankar is right

Another variant:

<script>
  function onClick() {
    location = "b.html";
    return false;
  }
</script>
<a href="#" onclick="return onClick();">Link</a>


Or you can point the link at the function and skip the onclick event:

<script>
  function onClick() {
    location = "b.html";
    return false;
  }
</script>
<a href="javascript:onClick();">Link</a>
0

精彩评论

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

关注公众号