动态创建多个div并为每个使用jQuery

问题描述:

我坚持在那里我不能够创建具有不同的CSS多个div使用循环属性的问题,分配不同的CSS属性。如果有人指导我,这将会非常有帮助。动态创建多个div并为每个使用jQuery

我只在我的容器内创建一个div。我认为问题在于我追加我的子div的方式。

预先感谢您。

+0

是array.length大于1? – arop

+0

@arop是的,它是一个长度为4 – jstandshigh

+0

你的问题是创造了新的元素或样式他们的? –

$(".container").append('<div class="event" ><a>Sample text</a></div>'); 
$(".event").css("top",start+"px"); 
$(".event").css("width","94%"); 
$(".event").css("height",heightVal+"px"); 

您需要上下文化您的查找。你正在容器中创建一个事件,但是你选择每个事件来改变它的CSS。逻辑更改为可能...

var $event = $('<div class="event" ><a>Sample text</a></div>'); 
$(".container").append($event); 
$event.css("top",start+"px"); 
$event.css("width","94%"); 
$event.css("height",heightVal+"px"); 
+0

非常感谢你的工作! – jstandshigh

+0

@jstandshigh您是否看到我的解决方案使用多个css对象? – HenryDev

我觉得你的问题就来了,因为你动态创建的元素,它们试图通过类选择应用一些样式,这是行不通的。

我想这样做:

var new_element = $('<div class="event" ><a>Sample text</a></div>'); 
$(".container").append(new_element); 
$(new_element).css('color', 'red'); 
+0

非常感谢你的工作! – jstandshigh

您可以创建一个容器和追加你的div在那里。另外,最好将一个对象用于多种样式(CSS)。看看我的解决方案。希望能帮助到你 :)。

$(document).ready(function() { 
 

 
for (var i = 1; i <= 5; i++) { 
 
    $('#container').append('<div class="event" ><a>Sample text</a></div>').css({ 
 
    "width":"94%", 
 
    "color":"blue" 
 
    }); 
 
    } 
 

 
    $(".event:eq(2)").css({ 
 
    "background": "red" , 
 
    "color":"green", 
 
    "width":"300px" 
 
    }); 
 
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> 
 
<div id="container"></div>

+0

非常感谢您的帮助。 – jstandshigh

+0

@jstandshigh你能至少投我的答案吗?谢谢 – HenryDev

+0

我upvoted你的答案。 – jstandshigh