简体   繁体   中英

Issue on Applying CSS to Append Function on Element Creation

Can you please take a look at this Demo and let me know how to fix the issue on this code?

<div id="out"></div>

<script>
$(document).ready(function () {
    var colors = new Array("#FFF", "#CCC", "#7FFF00");
    for (var i = 0; i < colors.length; i++) {
        $("#out").append('<div class="box"></div>');
        $(".box").css("background-color",colors[0]);
    }
});
</script>

what I am trying to do is generating div elements based on an array length and set the background of them from the colors array

Thanks

The problem is, inside the loop, you are targetting all .box elements instead of targetint the element which was recently added.

You can use .appendTo() instead to return the recently added element and use that reference to make the css changes

$(document).ready(function () {
    var colors = new Array("#FFF", "#CCC", "#7FFF00");
    for (var i = 0; i < colors.length; i++) {
        var $el = $('<div class="box">1</div>').appendTo("#out");
        $el.css("background-color", colors[i]);//also need to use the index of the array instead of the hard coded 0
    }
});

Demo: Fiddle

Also try

jQuery(function ($) {
    var colors = new Array("#FFF", "#CCC", "#7FFF00");
    $.each(colors, function (i, color) {
        var $el = $('<div class="box">1</div>').appendTo("#out");
        $el.css("background-color", color);
    })
});

Demo: Fiddle

您应该使用i没有0

$(".box").css("background-color",colors[i]);

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