2011-06-21 34 views
0

我使用jQuery来动态更改div上的背景图像。这里是我的代码:使用jQuery .css()变量

$.ajax({ 
    url: '/countries/' + currentHash, 
    type: 'GET', 
    dataType: 'html', 
    complete: function(xhr, textStatus) { 
     //called when complete 
    }, 
    success: function(data, textStatus, xhr) { 
     $('#info').empty(); 

     var country_id = $('div#country_id', data).text(); 
     $('#fancybox-outer').css('background', "#ffffff url(\"/system/backgrounds/" + country_id + "/large.jpg\") no-repeat top right"); 
     // $('#fancybox-outer').css('background', '#ffffff url("/system/backgrounds/4/large.jpg") no-repeat top right'); 

     $.fancybox(
      $('#info').html(), 
      { 
       autoDimensions : false, 
       width   : '800', 
       height   : '600', 
       speedIn    : 600, 
       speedOut    : 200, 
       // scrolling    : 'no', 
       padding : 0, 
       centerOnScroll : true, 
       overlayColor : '#333333', 
       overlayOpacity : 0.8, 
       transitionIn : 'fade', // 'elastic', 'fade' or 'none' 
       transitionOut : 'elastic', // 'elastic', 'fade' or 'none' 
       hideOnOverlayClick : false, 
      } 
     );              

    } 
}); 

其他所有工作都很好的代码。我实际上抽出了一些东西,以便你阅读起来更容易。它在div中获得country_id。我试着将country_id变量附加到页面上的div上,以确保它能够得到它。但这部分只是不工作:

var country_id = $('div#country_id', data).text(); 
    $('#fancybox-outer').css('background', "#ffffff url(\"/system/backgrounds/" + country_id + "/large.jpg\") no-repeat top right"); 
    // $('#fancybox-outer').css('background', '#ffffff url("/system/backgrounds/4/large.jpg") no-repeat top right'); 

注释掉的部分工作。有关我应该做什么的想法?

谢谢!

+0

什么是在这一点上你的COUNTRY_ID变量的值在代码中?你确定它包含你所期望的吗? –

+1

它以什么方式“不工作”?你得到一个JavaScript错误,网址没有设置? div的url是错误的? – KingErroneous

+0

你可以显示html吗? –

回答

2

尝试修改报价是这样的:

$('#fancybox-outer').css('background', '#ffffff url("/system/backgrounds/' + country_id + '/large.jpg") no-repeat top right'); 

您可能还需要确保COUNTRY_ID不包含任何空白

var country_id = $('div#country_id', data).text().trim(); 
+0

这是修剪!非常感谢! – Marc