Perché "return false" non funziona?
importanza: 3
Perché nel seguente codice return false non funziona?
<script>
function handler() {
alert( "..." );
return false;
}
</script>
<a href="/?originalUrl=https%3A%2F%2Fit.javascript.info%2F%26quot%3Bhttps%3A%2F%2Fw3.org%26quot%3B%2520onclick%3D%26quot%3Bhandler()%26quot%3B%26gt%3Bil%2520browser%2520andr%25C3%25A0%2520su%2520w3.org%26lt%3B%2Fa%26gt%3B%253C%2Fcode">
Il browser navigherà verso all’URL al click, ma non è ciò che vogliamo.
Come si può sistemare?
Quando il browser legge un attributo on* come onclick, crea il gestore dal suo contenuto.
Nel caso di onclick="handler()" la funzione sarà:
function(event) {
handler() // il contenuto del click
}
Possiamo osservare che il valore restituito da handler() non viene usato e non influenza il risultato.
Il fix è semplice:
<script>
function handler() {
alert("...");
return false;
}
</script>
<a href="/?originalUrl=https%3A%2F%2Fit.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">
Possiamo anche usare event.preventDefault(), come in questo esempio:
<script>
function handler(event) {
alert("...");
event.preventDefault();
}
</script>
<a href="/?originalUrl=https%3A%2F%2Fit.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">