jQuery .each 返回 TypeError: 无法调用未定义的方法 'indexOf'

jQuery .each returning TypeError: Cannot call method 'indexOf' of undefined

本文关键字:方法 indexOf 未定义 调用 返回 each TypeError jQuery      更新时间:2023-09-26

我想做的是找到页面上包含https的所有链接,如果它们这样做,请做一些事情。但是,当我使用控制台在 Chrome 中运行它时,我收到一个类型错误:无法调用 null 的方法"indexOf"。我已经在SO上读到,如果一个值作为未定义返回,那么它会破坏函数。所以我想知道如何忽略没有点击值的 https?(顺便说一句,我正在慢慢学习javascript/jquery)。谢谢

$("a[href*='https:']").each(function(){
    var blah = $(this).attr('onclick');
    console.log(blah);
    if(blah.indexOf('_gaq') === 0){
        console.log('contains gaq');
    }
});

您可以使用选择器

$("a[href*='https:'][onclick]")

仅选择在其 href 中同时具有"https"和"onclick"属性的锚标记。

参考:多属性选择器

首先检查blah是否存在:

$("a[href*='https:']").each(function () {
    var blah = $(this).attr('onclick');
    if (blah && blah.indexOf('_gaq') === 0) {
        console.log('contains gaq');
    }
});

显然没有为某些<a>定义onclick。您可以添加逻辑来检查onclick是否存在。

$("a[href*='https:']").each(function () {
    var blah = $(this).attr('onclick');
    if (blah !== undefined) {
        if (blah.indexOf('_gaq') === 0) {
            console.log('contains gaq');
        }
    }
});