fix needed regarding Uncaught TypeError: Cannot read property 'substr' of undefined

fix needed regarding Uncaught TypeError: Cannot read property 'substr' of undefined

下面的脚本当前用于提取 URL 并在鼠标悬停时执行图像交换。但是,我目前遇到未捕获的类型错误:

cannot read property 'substr' of undefined

密码是:

<script>
jQuery(document).ready(function(){
    jQuery('.hover_box_wrapper').mouseenter(function(){
        var img_src = jQuery(this).parent().parent().parent().find('.hover2 img').attr('src');
        var img_src_s= img_src.substring(0,img_src.lastIndexOf("?"));
        var img_href = jQuery(this).parent().attr('href');
        var img_src_set = jQuery(this).parent().parent().parent().find('.hover2 img').attr('srcset');
        var src = jQuery('.center123').find('img').attr('src');
        var res = src.split(" ");
        var src_first = res[0];
         src_first = src_first.substring(0,src_first.lastIndexOf("?")); 

        jQuery('.center123').find('img').attr('src',img_src_s);
        jQuery('.center123').find('img').attr('srcset',src_first);

        //var img_html = jQuery('.center123').find('.vc_single_image-wrapper').html();
        //jQuery('.center123').find('.vc_single_image-wrapper').html('');
        jQuery('.center123').find('.vc_single_image-wrapper').html('<a href="'+ img_href + '"><img src="'+ img_src_s+'" srcset="'+ src_first +'" /></a>');
    });
});

你的错误隐藏在这里,在这段代码中,如果你逐行调试它:

var src = jQuery('.center123').find('img').attr('src');
var res = src.split(" ");
var src_first = res[0];

如果 没有 元素被发现,你将找不到 src 属性,这等于 undefined 值存储在 src_first 多变的。

您需要对存储在 res[0] 中的结果进行额外检查。 split(" ") 仅适用于类型 {String},不能应用于 undefined

最简单的附加检查可以编码为:

// ...
var src = jQuery('.center123').find('img').attr('src');
if (! src) { // <== here's the additional check, the simplest case possible
    return;
}
var res = src.split(" ");
var src_first = res[0];
// ...