簡體   English   中英

如何讓一個 HTML<a>元素有一個 href 但默認為 Onclick?</a>

[英]How To Make A HTML <a> Element Have A href But Default to Onclick?

我的 html 頁面中有一個<a> 我用 JavaScript 編寫了一個自定義重定向器,因此當您單擊按鈕時,它會運行一個 javascript 函數,該函數在重定向您之前執行重要任務。 例如:

 function go(page) { alert("You are being redirected!") // Important things here, such as saving open(page, target="_self") }
 a { color: blue; text-decoration: underline; cursor: pointer; }
 Link: <a onclick="go('/nextPage')">Click me to go to the next page!</a>

在上面的示例中,鏈接運行腳本以執行函數,然后打開 URL。 但是,如果您右鍵單擊該鏈接,則沒有像其他鏈接那樣的“在新標簽頁中打開”選項,因為它沒有href 如果有href ,它會在不運行 js 的情況下轉到下一個選項卡。 是否有可能讓它有一個 href 以便右鍵單擊工作,但仍然運行 JS? 所以基本上,它會給onclick事件授權,除非發生右鍵單擊,否則不會運行href

我嘗試刪除onclick並使用href="javascript:go('/nextPage);" 相反,但右鍵單擊會使其轉到about:blank#blocked in chrome。

不要使用onclick 相反,在所有錨標簽上添加一個click事件偵聽器,以防止默認操作(通過e.preventDefault() )並調用go函數。

 function go(page) { alert("You are being redirected!") // Important things here, such as saving open(page, target = "_self") } document.querySelectorAll('a').forEach((f) => { f.addEventListener('click', function(e) { e.preventDefault(); go(this.getAttribute('href')); }) })
 a { color: blue; text-decoration: underline; cursor: pointer; }
 Link: <a href="https://stacksnippets.net">Click me to go to the next page!</a>

對 HTML 感到抱歉,我不得不嘗試不同的編輯器來檢查結果。

試試這個

 <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>JS Bin</title> </head> <script> function go(page) { alert("You are being redirected!") // Important things here, such as saving return false; // equivalent to preventDefault } </script> <body> <a href='http://www.example.com' onclick='return go()'>Click me to go to the next page!</a> </body> </html>

要么

 <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>JS Bin</title> </head> <script> function go(event) { if( !confirm(`Redirect to ${event.target.href} ?`) ) event.preventDefault(); } </script> <body> <a href='/example' onclick="go(event)"> Click me to go to the next page! </a> </body> </html>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM