简体   繁体   中英

Items not being added to array?

So this should be super simple, but I have no idea whats wrong.

    var imageColors = [];

    $('.portfolio-image').each(function(index, el) {
        RGBaster.colors(this, {
          success: function(payload) {
            console.log(payload.dominant);
            imageColors.push(payload.dominant);
          }
        });
    });

    $('.portfolio-title').each(function(index, el) {
        $(this).css('color', 'imageColors[index]');
    });

});

So the code above has an array which should store colors from a set of images. Then we cycle through some text and set the text color to be the dominant color from each image in the order they are visible.

Anyways, the problem is no matter how I "add" something the imageColors array, nothing is in it. When I run a console.log of the length of the array it's always 0. So can someone explain why nothing is being added?

Since you have a success callback passed to colors plugin, it looks like a async method that means when the second each block is executed the array may not be filled with the desired data.

One solution here is to set the color css inside the callback like

var imageColors = [];
var $titles = $('.portfolio-title');
$('.portfolio-image').each(function (index, el) {
    RGBaster.colors(this, {
        success: function (payload) {
            imageColors.push(payload.dominant);
            $titles.eq(index).css('color', payload.dominant);
        }
    });
});

Take off String value

$.each(imageColors, function(index, el) {
    $('.portfolio-title').css('color', imageColors[index]);
});

ERROR 'imageColors[index]' CORRECTION imageColors[index]

You have to go with this

$('.portfolio-title').each(function(index, el) {
    $(this).css('color', imageColors[index]); \\ remove single quote
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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