給Javascript代碼“預留退路”

來源:互聯網
上載者:User

所謂給Javascript代碼“預留退路”意思就是當使用者將瀏覽器的Javascript功能禁用的時候,頁面中使用了Javascript的地方要能夠以變通的方式得以運行,而不能讓使用者看到出錯或是點擊某按鈕而毫無反應,這也是使用者體驗很重要的一部分。 舉個簡單的例子來說,點擊頁面中的一個連結可以彈出一個新的頁面,我們通常會使用window.open,代碼如下:

<a href="#" onclick="openWin('http://baidu.com');">百度</a><script type="text/javascript">    function openWin(url) {        window.open(url, "openwin", "width=600,height=400");    }</script>

<a href="javascript:openWin1('http://baidu.com');" >百度</a><script type="text/javascript">    function openWin(url) {        window.open(url, "openwin", "width=600,height=400");    }</script>

上面的兩種方法第一種將href的值設定為#,第二種使用偽協議javascript: ,這兩種做法都不是很好,沒有“預留退路”,當使用者將瀏覽器的Javascript禁用後,點選連結都不是我們想要的結果,正確的做法如下:

<a href="http://baidu.com/"  onclick="openWin(this.getAttribute('href'));return false;" >百ù度è</a> <script type="text/javascript">     function openWin1(url) {         window.open(url, "openwin", "width=600,height=400");     } </script>

改進後的方法在禁用Javascript後,也會開啟href中的連結地址,只是開啟檔案有所不同,相比上面兩種已經好多了。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.