我正在尝试编写一段代码,当单击一个按钮时,它会检查图像列表,检查其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();
            }
        });
});

最佳答案

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

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


从文档:


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


有趣的是,本机getAttribute函数针对尚未设置的属性返回null。 jQuery,由于某种原因,explicity checks for this并返回undefined

ret = elem.getAttribute(name);

// Non-existent attributes return null, we normalize to undefined
return ret === null ? undefined : ret;

10-04 22:25
查看更多