简体   繁体   English

将CSS应用于元素创建附加功能的问题

[英]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 我想做的是基于数组长度生成div元素,并从colors数组设置它们的背景

Thanks 谢谢

The problem is, inside the loop, you are targetting all .box elements instead of targetint the element which was recently added. 问题是,在循环内,您将所有.box元素作为目标,而不是targetint最近添加的元素。

You can use .appendTo() instead to return the recently added element and use that reference to make the css changes 您可以改用.appendTo()返回最近添加的元素,并使用该引用进行css更改

$(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]);

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

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