将以下代码保存为test.html,用浏览器打开即可测试

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>preventDefault() 方法防止打开不是本站的链接URL。</title>
<script src="http://code.jquery.com/jquery-1.10.2.js"></script> </head> <body>
<a href="www.w3school.com.cn/localhost">www.w3school.com.cn/localhost</a><br />
<a href="http://www.w3school.com.cn/localhost">http://www.w3school.com.cn/localhost</a><br />
<a href="http://baidu.com/https://baidu.com">http://baidu.com/https://baidu.com</a><br />
<a href="http://baidu.com/">http://baidu.com/</a><br />
<a href="http://localhost/">http://localhost/</a><br />
<p>preventDefault() 方法防止打开不是本站的链接URL。</p>
<!--方法一-->
<script type="text/javascript">
var ym = window.location.host;//获取当前网址域名部分
//alert(ym);
$("a").each(function(){
var url = $(this).attr("href").replace("https://","").replace("http://","").split("/")[0];
//alert(url);
if(url.indexOf(ym)<0){ //如果不是站内链接
$(this).click(function(event){
event.preventDefault();
});
}
});
</script>
<!--方法二-->
<script type="text/javascript">
var ym = window.location.host;//获取当前网址域名部分
//alert(ym);
$("a").click(function(event){
var url = $(this).attr("href").replace("https://","").replace("http://","").split("/")[0];
//alert(url);
if(url.indexOf(ym)<0){ //如果不是站内链接
event.preventDefault();
}
});
</script>
</body>
</html>

最新文章

  1. Matlab-Octave中绘制网格图和等高线:mesh 和 surf
  2. 从设计到开发,硅谷技术专家教你做“声控”APP
  3. Win10新版下virtualbox双击没有反应
  4. winrt控件
  5. 使用Hexo搭建github博客步骤,超简便
  6. MediaPlayer 音频播放 示例
  7. 集成Dubbo服务(Spring)
  8. L9-2.安装mysql数据库
  9. 用PS绿化版出现“请卸载并重新安装该产品”的解决方法
  10. STM32 + RT Thread OS 学习笔记[二]
  11. Prince2学习有感:PRINCE2项目管理到底是什么?
  12. CSS中可以继承和不可继承的常见属性
  13. java客户端Jedis操作Redis Sentinel 连接池
  14. 登录以及发送微信消息itchat 库
  15. 使用Jenkins部署asp.net core
  16. 唉 调皮的ListView
  17. javascript for循环 日期 select
  18. asp.net core Session的测试使用心得及注意事项
  19. pyinstaller spec
  20. 【webpack】webpack.base.conf.js基础配置

热门文章

  1. 自定义配置文件读取产生的“无法添加已属于该配置的 ConfigurationSection”异常解决办法
  2. Java学习笔记之ArrayList基本用法
  3. linux计划crontab
  4. Python学习之==&gt;面向对象编程(二)
  5. Java基础面试题集(二)
  6. pcap中不同包功能
  7. 线性模型-线性回归、Logistic分类
  8. Metinfo4.0 /member/save.php 任意用户密码修改
  9. Systemd vs SysVinit
  10. Vim命令合集(四)