A-A+

js中不使用blank在新窗口打开链接的方法

2016年10月16日 前端设计 暂无评论 阅读 5 views 次

有很多朋友会发现在一些网站会碰到很多blank这样的标签直接加在了a之后了,下面我来给各位朋友介绍三种不在a标签加blank的方法,有需要了解的朋友可参考。

思路,在页面载入以后,将rel含有external的a标签,通过js加上target=”_blank“。下面提供jquery方法,代码如下:

  1. <script type="text/javascript">  
  2. <!--//--><![CDATA[//><!--  
  3.       $(document).ready(function() {  
  4.         // Find all external links and let them open in a new window.  
  5.         $("a.external-link").each(function() {//xiariboke.net  
  6.           $(this).click(function() {  
  7.             window.open($(this).attr("href"));  
  8.             return false;  
  9.           });  
  10.         });  
  11.       });  
  12.       
  13. //--><!]]>  
  14. </script>  

html,代码如下:

  1. <p>点我在新窗口打开链接  
  2. <a href="https://www.xiariboke.net"  class="external-link">网页制作教程</a>  
  3. </p>  

js原生方法如下:

  1. <script type="text/javascript">  
  2.  function externalLinks() {  
  3.   if (!document.getElementsByTagName) return;  
  4.    var anchors = document.getElementsByTagName("a");  
  5.    for (var i=0; i<ANCHORS.LENGTH; i++) {  
  6.    var anchor = anchors;  
  7.    if (anchor.getAttribute(“href”) &&  
  8.    anchor.getAttribute(“rel”) == “external”)  
  9.    anchor.target = "_blank";  
  10.   }  
  11.  }  
  12.  window.onload = externalLinks;  
  13. </script>  

如果你不使用js或jquery来打开新窗口我们可以直接如下,在页面head结束处加上:

  1. <base target="_blank" />  
标签:

给我留言