بازگشت به درس
این محتوا تنها در این زبان‌ها موجود است: English, Español, Français, Indonesia, Italiano, 日本語, 한국어, Русский, Українська, Oʻzbek, 简体中文. لطفاً به ما

Why in the code below return false doesn’t work at all?

<script>
  function handler() {
    alert( "..." );
    return false;
  }
</script>

<a href="/?originalUrl=https%3A%2F%2Ffa.javascript.info%2F%26quot%3Bhttps%3A%2F%2Fw3.org%26quot%3B%2520onclick%3D%26quot%3Bhandler()%26quot%3B%26gt%3Bthe%2520browser%2520will%2520go%2520to%2520w3.org%26lt%3B%2Fa%26gt%3B%253C%2Fcode">

The browser follows the URL on click, but we don’t want it.

How to fix?

When the browser reads the on* attribute like onclick, it creates the handler from its content.

For onclick="handler()" the function will be:

function(event) {
  handler() // the content of onclick
}

Now we can see that the value returned by handler() is not used and does not affect the result.

The fix is simple:

<script>
  function handler() {
    alert("...");
    return false;
  }
</script>

<a href="/?originalUrl=https%3A%2F%2Ffa.javascript.info%2F%26quot%3Bhttps%3A%2F%2Fw3.org%26quot%3B%2520onclick%3D%26quot%3Breturn%2520handler()%26quot%3B%26gt%3Bw3.org%26lt%3B%2Fa%26gt%3B%253C%2Fcode">

Also we can use event.preventDefault(), like this:

<script>
  function handler(event) {
    alert("...");
    event.preventDefault();
  }
</script>

<a href="/?originalUrl=https%3A%2F%2Ffa.javascript.info%2F%26quot%3Bhttps%3A%2F%2Fw3.org%26quot%3B%2520onclick%3D%26quot%3Bhandler(event)%26quot%3B%26gt%3Bw3.org%26lt%3B%2Fa%26gt%3B%253C%2Fcode">