GET参数是URL中问号(?)后面的部分,用于向服务器传递数据。格式通常为key=value
,多个参数用&
连接,例如:example.com/page?param1=value1¶m2=value2
。
// 选择所有包含特定GET参数的链接
function selectLinksWithParam(paramName) {
const allLinks = document.getElementsByTagName('a');
const matchingLinks = [];
for (let link of allLinks) {
if (link.href.includes('?')) {
const url = new URL(link.href);
if (url.searchParams.has(paramName)) {
matchingLinks.push(link);
}
}
}
return matchingLinks;
}
// 使用示例:选择所有包含"id"参数的链接
const linksWithId = selectLinksWithParam('id');
console.log(linksWithId);
// 使用jQuery选择包含特定GET参数的链接
function selectLinksWithParamJQuery(paramName) {
return $('a[href*="?"]').filter(function() {
const url = new URL(this.href);
return url.searchParams.has(paramName);
});
}
// 使用示例
const $linksWithId = selectLinksWithParamJQuery('id');
console.log($linksWithId);
// 使用正则表达式选择包含特定GET参数的链接
function selectLinksWithParamRegex(paramName) {
const allLinks = document.getElementsByTagName('a');
const matchingLinks = [];
const regex = new RegExp(`[?&]${paramName}(=|&|$)`);
for (let link of allLinks) {
if (regex.test(link.href)) {
matchingLinks.push(link);
}
}
return matchingLinks;
}
// 使用示例
const linksWithIdRegex = selectLinksWithParamRegex('id');
console.log(linksWithIdRegex);
%3D
代表=
,需要考虑解码#
后面的部分不会影响参数匹配如果需要同时匹配参数名和参数值:
function selectLinksWithParamAndValue(paramName, paramValue) {
const allLinks = document.getElementsByTagName('a');
const matchingLinks = [];
for (let link of allLinks) {
try {
const url = new URL(link.href, window.location.href);
if (url.searchParams.get(paramName) === paramValue) {
matchingLinks.push(link);
}
} catch(e) {
console.warn('Invalid URL:', link.href);
}
}
return matchingLinks;
}
// 使用示例:选择所有id=123的链接
const linksWithId123 = selectLinksWithParamAndValue('id', '123');
没有搜到相关的文章