2013-06-26 37 views
0

我使用以下函数使用ajax响应创建动态元素。如何更改为默认背景图像

function itemGroupSelection(elem,majorGroupId,itemGroupId){ 

    var itemGroup; 
    var majorGroup; 

    if(elem == undefined || elem == null || elem == ""){ 
     var itemGroup = itemGroupId; 
     var majorGroup = majorGroupId; 
    }else if(majorGroupId == null && itemGroupId == null){ 
     var itemGroup = elem.attr("id"); 
     var majorGroup = elem.attr("majorgroup"); 
    } 



    $('.breadcrumb a').removeClass('active'); 

    if(elem == ""){ 
     $('.breadcrumb a').first().addClass('active'); 
    }else{ 
     elem.addClass('active'); 
    } 

    var selectedOutlet = $('#outlets select').children(":selected").attr("id"); 
    $('.item').show(); 
    $('.breadcrumb').show('1'); 
    var data = "majorGroupId=" + majorGroup + "&itemGroupId=" + itemGroup + "&outletCode=" + selectedOutlet; 

    if(selectedOutlet == undefined){ 
     getSystemMessage('Please select an outlet.'); 
    }else{ 
     ajaxCall("/getItems","POST",data,function(result){ 
      var element = $('#model-item').find('.item').first(); 
      $('#item-list-section').empty(); 

      for(var i = 0; i < result.items.length; i++){ 
       var clone = element.clone(); 

       clone.attr("id", result.items[i].itemId); 
       clone.find('.item-price').html("<h4>" + result.items[i].rate.toFixed(2) + "</h4>"); 
       if(result.items[i].itemName.length >= 20){ 
        clone.find('.item-name').css('overflow','hidden'); 
        clone.attr('title', result.items[i].itemName) 
       } 
       clone.find('.item-name').html("<h4>"+ result.items[i].itemName + "</h4>"); 
       clone.css('background-image','c:/zharaimages/' + result.items[i].itemId + '/image.jpg'); 

       clone.draggable({ 
        revert : false, 
        zIndex: 1, 
        containment: "window", 
        opacity: 0.5, 
        cursor: "move", 
        helper: function() { return $(this).clone().appendTo('body').show(); } 
       }); 
       $('#item-list-section').append(clone); 
      } 
     }); 
    } 


} 

使用以下命令我尝试选择本地光盘中的背景图像。

clone.css('background-image','c:/zharaimages/' + result.items[i].itemId + '/image.jpg'); 

如何在定义的路径中没有图像时切换到默认图像。我正在使用jQuery 1.9。

+2

为什么使用本地磁盘上的文件?这应该如何工作? –

回答

0

您需要处理onerror事件这一形象的,每当文件不能被发现,这将发生:

$('#image').error(function(){ 
    $(this).off('error'); // otherwise, inexistence of the default image is a real pain 
    $(this).attr('src', 'http://www.google.ca/images/srpr/logo4w.png'); 
}); 

看看这个工作FIDDLE


然后,

在您的情况

,你可以有这样的事情:

var path='the path'; 

clone.css('background-image', 'url('+path+')'); 
$('<img src="'+path+'" />').error(function(){ 
    $(this).off('error'); 
    clone.css('background-image', 'url('+default_path+')'); 
}); 

希望这有助于:-)

0

尝试使用IMG的onerror的属性,如果在src属性中给出的链接无法加载,错误的ur函数被调用,你可以在那里设置你的默认图像(w3schools.com/jsref/event_img_onerror.asp)