1

What I'm trying to do is find all of the links on a page that contain https and if they do, do something. However, when I run this in Chrome using console, I get a Type Error: Cannot call method 'indexOf' of null. I've read on SO that if a value is returned as undefined, then it breaks the function. So I'm wondering how do I ignore https that do not have a value for onclick? (btw, I'm slowly learning javascript/jquery). Thanks

$("a[href*='https:']").each(function(){
    var blah = $(this).attr('onclick');

    console.log(blah);

    if(blah.indexOf('_gaq') === 0){
        console.log('contains gaq');
    }
});
4

3 回答 3

2

您可以使用选择器

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

仅选择在其 href 中具有“https”和“onclick”属性的锚标记。

参考:多属性选择器

于 2013-09-16T23:13:00.880 回答
2

首先检查是否blah存在:

$("a[href*='https:']").each(function () {
    var blah = $(this).attr('onclick');

    if (blah && blah.indexOf('_gaq') === 0) {
        console.log('contains gaq');
    }
});
于 2013-09-16T23:25:45.873 回答
0

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

$("a[href*='https:']").each(function () {
    var blah = $(this).attr('onclick');

    if (blah !== undefined) {
        if (blah.indexOf('_gaq') === 0) {
            console.log('contains gaq');
        }
    }
});
于 2013-09-16T23:21:30.750 回答