如何使用jQuery点击事件提取a标签URL中的product_name值
从URL中提取product_name的解决方案
Hey there! 既然你的URL格式是固定的https://www.test.com/brand/product_name,那提取product_name其实很简单,给你几个靠谱的实现思路,直接套进你的现有代码里就行:
方法1:字符串分割(最直观)
你的URL结构非常规整,用split('/')把URL按斜杠拆分成数组后,最后一个元素就是你要的product_name。修改后的代码如下:
jQuery('.card_caption a').click(function(e){ // 临时阻止默认跳转方便测试,若需要保留跳转可注释此行 e.preventDefault(); console.log("working_fine"); var href = $(this).attr('href'); // 按斜杠分割数组,取最后一项 var productName = href.split('/').pop(); console.log(productName); // 此处即可查看提取出的product_name });
方法2:URL API解析(更稳健,适配复杂场景)
如果未来URL可能携带参数(比如https://www.test.com/brand/product_name?param=123),使用浏览器原生的URL对象解析会更稳妥,它能自动忽略多余参数:
jQuery('.card_caption a').click(function(e){ e.preventDefault(); console.log("working_fine"); var href = $(this).attr('href'); const url = new URL(href); // pathname返回的是/brand/product_name,分割后取最后一段 var productName = url.pathname.split('/').pop(); console.log(productName); });
方法3:正则表达式(自定义匹配规则)
要是你想更精准地匹配brand/之后的内容,也可以用正则表达式实现:
jQuery('.card_caption a').click(function(e){ e.preventDefault(); console.log("working_fine"); var href = $(this).attr('href'); // 匹配/brand/之后到URL结尾的所有内容 const matchResult = href.match(/\/brand\/(.+)$/); if(matchResult) { var productName = matchResult[1]; console.log(productName); } });
小提示
如果需要保留a标签的跳转功能,只需删除代码中的e.preventDefault()即可,提取变量的逻辑完全不受影响~
内容的提问来源于stack exchange,提问作者Praff
相关产品推荐
相关产品推荐

