Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
349 views
in Technique[技术] by (71.8m points)

js和jquery怎么获取点击链接的url?

点击一个超链接,怎么获取到它的url呢?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

分析一下这个问题
点击一个超链接,怎么获取到它的url呢

  1. 首先,需要获取信息,应当先保证其不跳转,即点击a标签时如何阻止其自动跳转到href的动作

  2. 获取url,即获取href属性的值

上面诸位同志回答2部分的都很好,但是都没处理自动跳转的问题

HTML

<!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标签的遍历了

JS

    <script type="text/javascript">
        function init() {
            document.getElementById('showHref').onclick = function() {
                console.log(this.href);
                /*下面两种写法任选其一*/
                // return false;
                event.preventDefault();
            };
        }
    </script>

Jquery

    <script type="text/javascript">
        $(document).on('click','#showHref',function() {
            console.log(this.href);
            /*或者*/
            // console.log($('#showHref').attr('href'));
            /*下面两种写法任选其一*/
            // return false;
            event.preventDefault();
        });
    </script>

全体a标签的遍历

@ 莲_涳栢__ 写的很好了,我这里再整合一下jquery的写法

JS

    <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>

Jquery

    <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那种古董好像也是无法兼容的┑( ̄Д  ̄)┍


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...