我知道有很多关于 Uncaught TypeError: Cannot read property 'match' of undefined
的类似问题,但我在其中任何一个中都没有找到解决方案专门针对我的问题。
这个脚本的目标是获取当前页面的 URL,使用正则表达式过滤掉查询字符串,找到页面上的所有链接,评估它们是否包含 ?
,然后追加相应的查询字符串。
我在 CodePen 上的测试取得了成功,但是,当我在网页上执行脚本时,它失败了,并在控制台中返回了 Uncaught TypeError
。
$(document).ready(function(){
var myRegexp = /\?([^]*)/gm;
var string_match = myRegexp.exec(window.location.href);
$('a').each(function(){
var href = $(this).attr('href');
href += (href.match(/\?/) ? '&' : '?') + string_match[1];
$(this).attr('href', href);
});
});
.match(/\?/) 处的错误标志? '&' : '?') + string_match[1];
,所以我...此时迷路了。为什么它只适用于代码 Playground ?
我修改的原代码来自here .
查看在 CodePen 上运行的代码 here .
非常感谢任何帮助,谢谢!
最佳答案
似乎评估发生在未定义的 href 上。可能您想进行防御性编码以检查 href 是否为真,然后对其进行评估匹配。或者您可以简单地返回 undefined href 而不做任何事情。
$(document).ready(function(){
var myRegexp = /\?([^]*)/gm;
var string_match = myRegexp.exec(window.location.href);
$('a').each(function(){
var href = $(this).attr('href');
href += href && (href.match(/\?/) ? '&' : '?') + string_match[1];
$(this).attr('href', href);
});
});
关于javascript - 为什么属性 'match' 未定义? (将查询字符串附加到页面链接),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50354998/