简体   繁体   English

jQuery的.css没有向正文添加background属性

[英]jQuery's .css isn't adding background attribute to body

As I'm trying to create a grid of images for my background, I need to be able to add the background-image attribute to the css of the body via jQuery, but it isn't working. 当我尝试为背景创建图像网格时,我需要能够通过jQuery将background-image属性添加到body的CSS中,但是它不起作用。 The following code returns the correct value, but all I see in the end is a blank page. 以下代码返回正确的值,但最后我看到的是空白页。

<body>
<script>

$('body').css('background-image', function() {

    var position = 0,
        image = '';

    for(var x=1; x<=4; x++) {
        // 4 rows

        for(var y=1; y<=8; y++) {
            // 8 columns

            position++;

            image += 'url(img/bg/' + position + '.jpg)'; 
            if(x<=4 && y<8) { image += ','; } 

        }

    }

    console.log(image);
    return image;

});


</script>

As you can see, I'm doing the script work after the body tag is created, so my understanding is that I don't need $(function(){}) to make things happen. 如您所见,在创建body标签之后,我正在执行脚本,因此我的理解是,我不需要$(function(){})来使事情发生。

Can anyone see what's keeping this from working? 谁能看到让它无法正常工作的原因?

Your if condition is wrong, so you're leaving out the , after every 8 URLs. 您的if条件错误,因此,每8个网址之后就省略了。

 $(function() { $('body').css('background-image', function() { var position = 0, image = ''; for (var x = 1; x <= 4; x++) { // 4 rows for (var y = 1; y <= 8; y++) { // 8 columns position++; image += 'url(img/bg/' + position + '.jpg)'; if (x < 4 || y < 8) { image += ','; } } } console.log(image); return image; }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 

The way I prefer to do things like this is to push the elements onto an array, then construct the string using array.join(',') . 我更喜欢做这样的事情,是将元素推到数组上,然后使用array.join(',')构造字符串。

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

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