扫码关注官方订阅号
点击一个超链接,怎么获取到它的url呢?
学习是最好的投资!
分析一下这个问题点击一个超链接,怎么获取到它的url呢
点击一个超链接,怎么获取到它的url呢
首先,需要获取信息,应当先保证其不跳转,即点击a标签时如何阻止其自动跳转到href的动作
获取url,即获取href属性的值
上面诸位同志回答2部分的都很好,但是都没处理自动跳转的问题
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>文档标题</title> </head> <body> <!-- some other code --> <a id='showHref' href="http://www.baidu.com">baidu</a> </body> </html>
假设是阻止特定标签的跳转,就不进行全体a标签的遍历了
<script type="text/javascript"> function init() { document.getElementById('showHref').onclick = function() { console.log(this.href); /*下面两种写法任选其一*/ // return false; event.preventDefault(); }; } </script>
<script type="text/javascript"> $(document).on('click','#showHref',function() { console.log(this.href); /*或者*/ // console.log($('#showHref').attr('href')); /*下面两种写法任选其一*/ // return false; event.preventDefault(); }); </script>
@ 莲_涳栢__ 写的很好了,我这里再整合一下jquery的写法
<script type="text/javascript"> function init() { Array.prototype.forEach.call(document.getElementsByTagName('a'), function(dom) { dom.onclick = function() { console.log(this.href); /*下面两种写法任选其一*/ // return false; event.preventDefault(); }; }); } </script>
<script type="text/javascript"> $(document).on('click','a',function() { console.log(this.href); /*或者*/ // console.log($('#showHref').attr('href')); /*下面两种写法任选其一*/ // return false; event.preventDefault(); }); </script>
document.querySelectorAll()比getElement(s)系列有更好的兼容性,而且写法更统一,建议使用。当然IE6那种古董好像也是无法兼容的┑( ̄Д  ̄)┍
document.querySelectorAll()
getElement(s)
[].forEach.call(document.querySelectorAll('a'),function(o){ o.onclick = function(){ var s = this.href; console.log(s); return !1; }; });
获取属性啊,用attr
$(document).on('click','a',function(){console.log($(this).attr('href'))})
var link = document.getElementById('linkId'); // 针对你点击的链接进行修改 link.href; // 或 link.getAttribute('href');
$('#linkId').attr('href')
微信扫码关注PHP中文网服务号
QQ扫码加入技术交流群
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
PHP学习
技术支持
返回顶部
分析一下这个问题
点击一个超链接,怎么获取到它的url呢首先,需要获取信息,应当先保证其不跳转,即点击a标签时如何阻止其自动跳转到href的动作
获取url,即获取href属性的值
上面诸位同志回答2部分的都很好,但是都没处理自动跳转的问题
HTML
假设是阻止特定标签的跳转,就不进行全体a标签的遍历了
JS
Jquery
全体a标签的遍历
@ 莲_涳栢__ 写的很好了,我这里再整合一下jquery的写法
JS
Jquery
补充
document.querySelectorAll()比getElement(s)系列有更好的兼容性,而且写法更统一,建议使用。当然IE6那种古董好像也是无法兼容的┑( ̄Д  ̄)┍获取属性啊,用attr
$(document).on('click','a',function(){console.log($(this).attr('href'))})
js
jquery