レッスンに戻る

「return false」が機能しない理由は?

importance: 3

以下のコードで「return false」が機能しない理由は?

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

<a href="https://w3.org" onclick="handler()">the browser will go to w3.org</a>

ブラウザはクリック時に URL に従いますが、私たちはそう望んでいません。

修正方法は?

ブラウザが "onclick" などの "on*" 属性を読み込むと、その内容からハンドラを作成します。

"onclick="handler()" に対して関数は

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

ここで "handler()" で返される値は使用されず、結果には影響しないことがわかります。

修正は簡単です

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

<a href="https://w3.org" onclick="return handler()">w3.org</a>

また、次のように "event.preventDefault()" を使用することもできます。

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

<a href="https://w3.org" onclick="handler(event)">w3.org</a>