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