我正在使用以下内容根据 url 中斜线后的最后一个单词创建一个 if 语句:
// Sticky
var match = location.search.match(/(\w+)$/)[0];
if (match === 'complete') {
$('p:has(audio)').addClass('sticky-child');
$('p:has(audio)').appendTo('.lesson_lang_switch');
}
问题是,首页的 URL 末尾没有任何单词(斜线后):
www.example.com/
所以我得到这个错误:
Uncaught TypeError: Cannot read property '0' of null
如何才能不出现错误?
最佳答案
您可以添加条件检查。即
var match = (location.search.match(/(\w+)$/))
? location.search.match(/(\w+)$/)[0]
: "";
if (match === 'complete') { // match will be "" if the above is false
$('p:has(audio)').addClass('sticky-child');
$('p:has(audio)').appendTo('.lesson_lang_switch');
}
关于javascript - 如何删除此 JavaScript 空错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28761670/