在JavaScript中,可以通过window.location
对象来获取当前页面的URL信息。以下是一些常用的属性和方法:
window.location.href
:window.location.origin
:window.location.pathname
:window.location.search
:?
后面的内容)。window.location.hash
:#
后面的内容)。如果需要解析查询字符串中的具体参数,可以使用以下方法:
function getQueryParamByName(name) {
var queryStr = window.location.search.substring(1); // 去掉开头的问号
var paramsArray = queryStr.split('&');
for (var i = 0; i < paramsArray.length; i++) {
var pair = paramsArray[i].split('=');
if (decodeURIComponent(pair[0]) === name) {
return decodeURIComponent(pair[1] || '');
}
}
return null;
}
// 使用示例
var userId = getQueryParamByName('userId');
console.log(userId);
window.location.href
实现页面跳转。window.location
会触发页面刷新或跳转,需谨慎使用。通过以上方法和注意事项,你可以灵活地在JavaScript中获取和处理URL相关信息。
领取专属 10元无门槛券
手把手带您无忧上云