jQuery/JavaScript to replace broken images

后端 未结 30 2567
我寻月下人不归
我寻月下人不归 2020-11-21 05:50

I have a web page that includes a bunch of images. Sometimes the image isn\'t available, so a broken image is displayed in the client\'s browser.

How do I use jQuery

30条回答
  •  醉梦人生
    2020-11-21 06:26

    Here is an example using the HTML5 Image object wrapped by JQuery. Call the load function for the primary image URL and if that load causes an error, replace the src attribute of the image with a backup URL.

    function loadImageUseBackupUrlOnError(imgId, primaryUrl, backupUrl) {
        var $img = $('#' + imgId);
        $(new Image()).load().error(function() {
            $img.attr('src', backupUrl);
        }).attr('src', primaryUrl)
    }
    
    
    
    

提交回复
热议问题