我试图让 jQuery 多次将一个 div append 到我的文档主体,但由于某种原因它只 append 了一个项目,我猜它是循环中的最后一个项目。
$(function(){
var howManyParticles = 11;
var bodyWidth = $(document).width();
var randomSpawn = Math.floor(Math.random() * bodyWidth) + 1;
var particleStyle = "background: lightgray;width: 10px;height: 10px;min-height: 10px;min-width: 10px;position: fixed;bottom: 0;left:" + randomSpawn + ";";
var particle = $("<div class='particle' style='"+ particleStyle +"'> </div>");
function spawnParticles(){
for(var i = 0; i <= howManyParticles; i++)
{
$('body').append(particle);
console.log('spawned');
}
}
spawnParticles();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
这只会在窗口中生成 1 个项目,我该怎么做才能生成与 i <= howManyParticles
一样多的项目?会是什么?
编辑:我的最终代码
我忘了我需要把 math.random
循环中的函数为生成的每个不同粒子提供不同的水平值!
$(function(){
var howManyParticles = 11;
var bodyWidth = $(document).width();
function spawnParticles(){
for(var i = 0; i <= howManyParticles; i++)
{
var randomSpawn = Math.floor(Math.random() * bodyWidth) + 1;
var particleStyle = "background: lightgray;width: 10px;height: 10px;min-height: 10px;min-width: 10px;position: fixed;bottom: 0;left:" + randomSpawn + ";";
var particle = $("<div class='particle' style='"+ particleStyle +"'> </div>");
$('body').append(particle);
}
}
spawnParticles();
});
最佳答案
在某些情况下,jQuery 会自动为您克隆一个节点,而在其他情况下则不会。在这种情况下,它不会这样做,因为它认为您实际上只是在尝试重新定位一个节点。
不是预先创建 DOM 元素,而是在循环中创建它。
$(function(){
var howManyParticles = 11;
var bodyWidth = $(document).width();
var randomSpawn = Math.floor(Math.random() * bodyWidth) + 1;
var particleStyle = "float: left; background: orange; border:1px solid red; width: 10px; height: 10px; margin: 5px;";
// Just a string------v
var particle = "<div class='particle' style='"+ particleStyle +"'> </div>";
function spawnParticles(){
for(var i = 0; i <= howManyParticles; i++)
{
// Append the string, which is turned into a new DOM element on each iteration
$('body').append(particle);
console.log('spawned');
}
}
spawnParticles();
console.log("FOUND %s PARTICLES", document.querySelectorAll(".particle").length);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
关于javascript - jQuery Append 只添加 1 项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41225160/