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>
网友评论文明上网理性发言 已有0人参与
发表评论: