<a href="http://www.baidu.com" id="btn">按鈕</a> <script> document.getElementById('btn').onclick = function () { console.log('執行要發生的事件邏輯'); } </script>
上述代碼中,點擊按鈕,就會跳轉到新的頁面。想要阻止頁面的跳轉:
在事件函數最后添加一句 return false
<a href="http://www.baidu.com" id="btn">按鈕</a> <script> document.getElementById('btn').onclick = function () { console.log('執行要發生的事件邏輯'); return false; } </script>
也可以在行內綁定這樣做:
<a href="http://www.baidu.com" id="btn" onclick="fn();return false;">按鈕</a> <script> function fn() { console.log('執行要發生的事件邏輯'); } </script>