偽鏈接實現方法記錄


  鏈接一般作為頁面跳轉的手段,但是有時候需要使用鏈接形式,來實現ajax請求(非直接的頁面跳轉),或者來實現特殊的頁面動畫效果(點擊鏈接,一段文字展開和收起)。

  總結起來有以下三種方法:

  1、給href屬性設置#,使得頁面保持在當前頁面, 但是頁面位置會跳轉到頂部,除非使用錨點跳轉到特殊位置。

    <a href="#">click here(#)</a><br/>

 

  2、使用javascript偽協議,給href屬性設置 javascript:void(0),詳情見下面網頁介紹

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/void

按照介紹是, 借助javascript:之后的最后一個表達式的值是否為undefined來判斷是否可以跳轉,如果是不能跳轉,否則能跳轉。

    <a href="javascript:void(0);" target="blank">click here(javascript:void(0);)</a><br/>
    <a href="javascript:undefined;" target="blank">click here(javascript:undefined;)</a><br/>


    <a href="javascript:void(0);'not undefined';" target="blank">click here(javascript:void(0);'not undefined';)</a><br/>
    <a href="javascript:'not undefined';void(0);" target="blank">click here(javascript:'not undefined';void(0);)</a><br/>

  最后一個表達式值得測試方法如下面:

         <script type='text/javascript'> 
         alert(eval("'not undefined';void(0);"))
         alert(eval("void(0);'not undefined';"))
         </script>

 

  3、直接架空href屬性的作用, 在onclick屬性中, 添加return false語句,這個語句會截止鏈接的原生行為,即href屬性失效。

    <a href="#" onclick="return false;" target="blank">click here(onclick="return false;")</a><br/>

  原理見《Javascript Best Practices》說明,http://www.javascripttoolbox.com/bestpractices/#onclick

The javascript code that runs within the onclick handler must return true or false (or an expression than evalues to true or false) back to the tag itself - if it returns true, then the HREF of the anchor will be followed like a normal link. If it returns false, then the HREF will be ignored. This is why "return false;" is often included at the end of the code within an onclick handler.

 

  最佳實踐推薦使用 onclick 替換 javascript偽協議,來觸發待執行的javascript代碼。 這樣做可以維持鏈接語義,在href中應該設置為頁面地址URL, 支持瀏覽器平穩退化。

When you want to trigger javascript code from an anchor <A> tag, the onclick handler should be used rather than the javascript: pseudo-protocol. 

 

下面給出完整測試代碼:

<html>
<head> 
         <style>
                 
         </style>
</head> 
<body>
    <a href="" target="blank">click here(normal archor)</a><br/>

    <a href="#">click here(#)</a><br/>


    <a href="javascript:void(0);" target="blank">click here(javascript:void(0);)</a><br/>
    <a href="javascript:undefined;" target="blank">click here(javascript:undefined;)</a><br/>


    <a href="javascript:void(0);'not undefined';" target="blank">click here(javascript:void(0);'not undefined';)</a><br/>
    <a href="javascript:'not undefined';void(0);" target="blank">click here(javascript:'not undefined';void(0);)</a><br/>


    <a href="#" onclick="return false;" target="blank">click here(onclick="return false;")</a><br/>

         <script type='text/javascript'> 
         //alert(eval("'not undefined';void(0);"))
         //alert(eval("void(0);'not undefined';"))
         </script>
</body>
</html>

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM