在JavaScript中,通过href
属性传递参数值是一种常见的做法,通常用于在页面间传递数据。以下是关于这一操作的基础概念、优势、类型、应用场景以及可能遇到的问题和解决方案:
通过href
传递参数,通常是在URL后面添加查询字符串(query string),格式为?key1=value1&key2=value2
。
http://example.com/page.html?key=value
。&
分隔,如http://example.com/page.html?key1=value1&key2=value2
。%20
。encodeURIComponent()
函数。sessionStorage
/localStorage
中。function addParamsToUrl(url, params) {
const queryString = Object.keys(params)
.map(key => `${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`)
.join('&');
return url + (url.includes('?') ? '&' : '?') + queryString;
}
const baseUrl = 'http://example.com/page.html';
const params = { key1: 'value1', key2: 'value2' };
const urlWithParams = addParamsToUrl(baseUrl, params);
console.log(urlWithParams); // 输出: http://example.com/page.html?key1=value1&key2=value2
function getParamsFromUrl(url) {
const params = new URLSearchParams(new URL(url).search);
const result = {};
for (const [key, value] of params.entries()) {
result[decodeURIComponent(key)] = decodeURIComponent(value);
}
return result;
}
const urlWithParams = 'http://example.com/page.html?key1=value1&key2=value2';
const params = getParamsFromUrl(urlWithParams);
console.log(params); // 输出: { key1: 'value1', key2: 'value2' }
通过上述方法,你可以方便地在JavaScript中通过href
传递和接收参数值。
领取专属 10元无门槛券
手把手带您无忧上云