使用 jQuery 在新窗口打開外部鏈接
來源:程序員人生 發(fā)布時(shí)間:2014-02-21 20:41:55 閱讀次數(shù):3381次
我們一般都希望在新窗口打開外部鏈接,這樣用戶就不需要離開網(wǎng)站就能訪問外部鏈接,但是如果每個(gè)外部鏈接都手工加上新窗口打開的屬性(target=”_blank”)的話,會(huì)讓人非常抓狂。使用 jQuery,我們只需要幾行代碼就能在新窗口中打開外部鏈接。
1. 找到外部鏈接
首先我們需要找到所有的外部鏈接,在 $(document).ready() 函數(shù)添加如下代碼:
$("a[href*='http://']:not([href*='"+location.hostname+"']),[href*='https://']:not([href*='"+location.hostname+"'])");
上面這段代碼查找 href 屬性是以 http:// 或者 https:// 開始的,并且不包含當(dāng)前域名(location.hostname)的鏈接(a)標(biāo)簽。這樣我們就不會(huì)獲取任何相對(duì)路徑或者絕對(duì)連接中含有當(dāng)前域名的內(nèi)部連接。
2. 給外部鏈接加上 “external” class
如果我們想給外部鏈接加上 “external” class,添加如下的代碼:
$("a[href*='http://']:not([href*='"+location.hostname+"']),[href*='https://']:not([href*='"+location.hostname+"'])")
.addClass("external");
上面的代碼給外部鏈接加上一個(gè) “external” Class ,這樣就可以使用 CSS 來樣式化外部鏈接了。
3. 讓外部鏈接在新窗口打開
如果你想外部鏈接在新窗口打開,繼續(xù)增加如下一行代碼:
$("a[href*='http://']:not([href*='"+location.hostname+"']),[href*='https://']:not([href*='"+location.hostname+"'])")
.addClass("external")
.attr("target","_blank");
上面的代碼給鏈接標(biāo)簽增加一個(gè) target 屬性,并且給他賦值為 _blank,這樣外部鏈接就能在新窗口打開。
生活不易,碼農(nóng)辛苦
如果您覺得本網(wǎng)站對(duì)您的學(xué)習(xí)有所幫助,可以手機(jī)掃描二維碼進(jìn)行捐贈(zèng)