我正在使用 jQuery 动态更改 div 上的背景图像。这是我的代码:
$.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');
注释掉的部分有效。关于我应该做什么有什么想法吗?
谢谢!
最佳答案
尝试像这样修改引号:
$('#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();
关于jquery - 将 jQuery .css() 与变量一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6428260/