×

学习下JS里的获取当前URL的方法

作者:andy0012019.11.26来源:Web前端之家浏览:5927评论:0
关键词:jsurl

jQuery可以通过使用Location对象的'href'属性来获得当前URL,该属性包含有关当前URL的信息。'href'属性返回一个包含当前页面完整URL的字符串。

语法:

$(location).attr('href')

示例1:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>如何使用jQuery获取当前URL?</title>
    </head>
    <body> 
    <h2 style="color: green">如何使用jQuery获取当前URL?</h2> 
    <p>单击按钮,获取当前页面URL</p> 
    <p> 当前URL为:<span class="output"></span></p> 
    <button id="btn">获取</button> 
    <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script> 
    <script> 
        $('#btn').click(function() { 
            currLoc = $(location).attr('href'); 
            document.querySelector('.output').textContent = currLoc; 
        }); 
    </script> 
</body> 
  
</html>

示例2:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>如何使用jQuery获取当前URL?</title>
    </head>
    <body> 
    <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script> 
    <script> 
        alert("host = " + $(location).attr('host') +  
              "\nhostname = " + $(location).attr('hostname') +  
              "\npathname = " + $(location).attr('pathname') +  
              "\nhref = " + $(location).attr('href') +  
              "\nport = " + $(location).attr('port') +  
              "\nprotocol = " + $(location).attr('protocol')); 
    </script> 
</body> 
</html>

您的支持是我们创作的动力!
温馨提示:本文作者系 ,经Web前端之家编辑修改或补充,转载请注明出处和本文链接:
https://jiangweishan.com/article/js898423048203948.html

网友评论文明上网理性发言 已有0人参与

发表评论: