简体   繁体   English

使用外部js文件设置背景图像

[英]Setting a background image with external js file

Im having an issue with setting my bacground image by using an external js code. 我有一个问题,通过使用外部js代码设置我的bacground图像。 this is the code of the js: 这是js的代码:

$(document).ready()
{
mazdaArr = new Array();
    for (i=1;i<6;i++)
    {
        mazdaArr[i-1]= new Image();
        mazdaArr[i-1].src = 'mazda/mazda'+[i]+'.jpg';
    }   
    $('mainContent').css('background-image','url(/mazda/mazda4.jpg)');
    $('mainContent').css('background-image', 'url(' + mazdaArr[3].src + ')');
    console.log(mazdaArr[3].src);
}

everything works fine but the css attr, since I can see at the console the right link and when I click it, the image will open up in new tag. 一切正常但css attr,因为我可以在控制台看到正确的链接,当我点击它时,图像将以新标签打开。 by that i guess the jquery call from html page is fine. 据我所知,来自html页面的jquery调用很好。

cant find what goes wrong here... 找不到这里出了什么问题......

A few things: 一些东西:

  • Looks like your string is concatinating an array literal, and not the integer i. 看起来你的字符串是一个数组文字,而不是整数i。 So 'string'+[]+'string' is effectively 'string' + new Array() + 'string' . 所以'string'+[]+'string'实际上是'string' + new Array() + 'string'
  • Your selector for mainContent needs to either be looking for a class or an ID so either .mainContent or #mainContent . 您的mainContent选择器需要查找类或ID,以便.mainContent#mainContent
  • Finally, you don't need to instantiate a new Image since jQuery will just update the CSS of the element with a new string for the background-image property. 最后,您不需要实例化新的Image因为jQuery将使用background-image属性的新字符串更新元素的CSS。

Try 尝试

$(document).ready(function() {
    var mazdaArr = [],
        i = 0;
    for (i; i<5; i++) {
        mazdaArr[i] = 'mazda/mazda'+ i +'.jpg';
    }   

    $('#mainContent').css('background-image', 'url(' + mazdaArr[3] + ')');

    console.log(mazdaArr[3].src);
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM