1

我正在尝试编写一段代码,当单击按钮时,它会检查图像列表,检查它是否具有“视频”的 id,如果有,则显示覆盖并删除那里的播放器。

我不断收到此错误:

Uncaught TypeError: Cannot call method 'indexOf' of undefined

这是代码:

$("#actions .btn").click(function(){
       $('.span img').each(function(){
            if($(this).attr('id').indexOf('video') != -1){
                var spanid = $(this).attr('id').replace(/video/, '');
                $(this).removeClass('hideicon');
                $('#mediaplayer' + spanid + '_wrapper').remove();
            }
        });
});
4

1 回答 1

1

如果您要查找的属性在元素上不存在,则该.attr()方法将返回。undefined我建议为您的情况添加额外检查:

var id = $(this).attr('id');
if(id && id.indexOf('video') != -1) {
    //OK!
}

从文档:

从 jQuery 1.6 开始,该.attr()方法返回undefined尚未设置的属性。

有趣的是,本机getAttribute函数会返回null尚未设置的属性。jQuery,出于某种原因,明确地检查这个并返回undefined

ret = elem.getAttribute(name);

// Non-existent attributes return null, we normalize to undefined
return ret === null ? undefined : ret;
于 2012-09-25T14:08:33.607 回答