jQuery.attr('src') replace not working in

2019-08-12 07:31发布

Strange issue. This code is working perfectly in Chrome / IE. However it does not work in FF 3.6 for some reason. Console shows no JS errors.

It is supposed to look for all images with a specific src attribute and on hover replace the src (I am aware of other approaches like css hover etc, there is a reason why I use this technique - it's not simply rollovers, it's animated video thumbs).

$("img[src*='libraries/phpthumb/phpThumbYT.php']").each(function(){
var t=$(this);
var src1= t.attr('src'); // initial src
var old_src = src1.substring(src1.lastIndexOf('media/'), src1.lenght);; // extract old source attr    
var media_id = old_src.substring(6,8); // extract media ID (directory name)
if ( old_src.indexOf("animation=1") != -1 )
{
    t.hover(function(){
        // on hover
        $(this).attr('src', 'libraries/phpthumb/phpThumbYT.php?w=131&h=92&far=C&iar=1&sfn=3&zc=C&f=gif&src=http://domain.name/media/'+media_id+'/preview.gif');  
    }, function(){
       // on rollout
        $(this).attr('src', src1);
    });
}
});

I suspect that there might be a problem with the selector maybe? Any ideas?

1条回答
ゆ 、 Hurt°
2楼-- · 2019-08-12 07:48

Finally found the solution.

The problem was that src1.lenght yelded a 'undefined' value. Although proposed by Alex as the source of the problem, documentation on W3C showed length as a valid property of string.

However, the problem itself was apparently caused by a different handling of the 'undefined' value in src1.substring(src1.lastIndexOf('media/'), src1.lenght);. Chrome and IE took the 'undefined' value simply as not present, therefor the string was parsed till the end. However in FF the substring function failed completely returning the whole string.

After isolating this problem I modified the script using sub-string with one argument only, as I actually wanted it to parse until the end, so the second parameter was not needed at all.

Beneath is the final code that works in Chrome + IE + FF.

$("img[src*='libraries/phpthumb/phpThumbYT.php']").each(function(){
var t=$(this);
var src1= t.attr('src'); // initial src
var old_src = src1.substring(src1.lastIndexOf('media/')); // extract old source attr    
var media_id = old_src.substring(6,8); // extract media ID (directory name)
media_id = media_id.replace('/',''); // trim '/' from the end of media_id in case the ID is < 10
if ( old_src.indexOf("animation=1") != -1 )
{
    t.hover(function(){
        // on hover
        $(this).attr('src', 'libraries/phpthumb/phpThumbYT.php?w=131&h=92&far=C&iar=1&sfn=3&zc=C&f=gif&src=http://slovoprekazdeho.sk/media/'+media_id+'/preview.gif');  
    }, function(){
       // on rollout
        $(this).attr('src', src1);
    });
}
});
查看更多
登录 后发表回答