HTML
<div id="test-external">
<p>如何学习<a href="http://jquery.com">jQuery</a>?</p>
<p>首先,你要学习<a href="/wiki/1022910821149312">JavaScript</a>,并了解基本的<a href="https://developer.mozilla.org/en-US/docs/Web/HTML">HTML</a>。</p>
</div>
JS引用
$('#test-external a').external();
JS函数构造
$.fn.external = function () {
return this.filter('a').each(function () {
var a = $(this);
var url = a.attr('href');
if (url && (url.indexOf('http://')===0 || url.indexOf('https://')===0)) {
a.attr('href', '#0')
.removeAttr('target')
.append(' <i class="uk-icon-external-link"></i>')
.click(function () {
if(confirm('你确定要前往' + url + '?')) {
window.open(url);
}
});
}
});
}
函数解析:
- filter(‘a’) HTML源码->
<a href="http://jquery.com">jQuery</a>
<a href="/wiki/1022910821149312">JavaScript</a>
<a href="https://developer.mozilla.org/en-US/docs/Web/HTML">HTML</a>
- url = a.attr(‘href’) url=
http://jquery.com
/wiki/1022910821149312
https://developer.mozilla.org/en-US/docs/Web/HTML
- 条件判断,只有链接1和链接3能够通过
- a.attr(‘href’, ‘#0’) a->
<a href="#0">jQuery</a>
<a href="#0">JavaScript</a>
<a href="#0">HTML</a>
这里解释一下,#0是为了组织点击字体跳转,毕竟目的是通过弹窗跳转。
- removeAttr(‘target’) a->去除target,因为target="_blank"会新开一个浏览器空白窗口,虽然我的HTML代码中没设target。
- .append(’ ') 链接文字后增加提示图标。
- confirm弹窗提示,跳转。