如何使用原生JavaScript获取list下a标签href中的email和pd参数值
原生JavaScript实现方案
这里推荐用事件委托的方式实现,不需要给每个a标签单独绑定事件,性能更优,同时也支持后续动态新增的a标签触发逻辑。
现代浏览器实现(推荐)
直接用原生URL和URLSearchParamsAPI解析参数,代码简洁易读:
document.addEventListener('click', function(e){ const target = e.target; // 判断点击元素为a标签,且处于id=list的容器内 if (target.tagName.toLowerCase() === 'a' && target.closest('#list')) { // 不需要跳转可保留该行,需要跳转请删除 e.preventDefault(); // 解析href参数 const urlObj = new URL(target.href, window.location.origin); const email = urlObj.searchParams.get('email'); const pd = urlObj.searchParams.get('pd'); // 此处写你拿到参数后的业务逻辑,示例为打印参数 console.log('获取到的email:', email); console.log('获取到的pd:', pd); } })
老旧浏览器兼容方案
如果需要兼容不支持URLSearchParams的IE等老旧浏览器,可以用正则匹配提取参数:
document.addEventListener('click', function(e){ const target = e.target; if (target.tagName.toLowerCase() === 'a' && target.closest('#list')) { e.preventDefault(); const href = target.getAttribute('href'); // 正则匹配提取参数 const email = href.match(/[?&]email=([^&]*)/) ? decodeURIComponent(href.match(/[?&]email=([^&]*)/)[1]) : null; const pd = href.match(/[?&]pd=([^&]*)/) ? decodeURIComponent(href.match(/[?&]pd=([^&]*)/)[1]) : null; console.log('获取到的email:', email); console.log('获取到的pd:', pd); } })
内容的提问来源于stack exchange,提问作者Bill
相关产品推荐
相关产品推荐

