不能在for循环中使用多个append() [英] Can't multiple append() within a for loop

查看:128
本文介绍了不能在for循环中使用多个append()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用以下代码将40个新的div元素附加到#colors div:

I'm trying to use the following code to append 40 new div elements to a #colors div:

$( document ).ready(function() {
    var $node = $("<div></div>");
    var $divg = $('#colors');
    for (var i = 1; i <= 40; i++) {
        $divg.append($node);
    }
});

最后,我得到以下信息:

At the end I get the following:

<div id="colors">
    <div></div>
</div>

有人可以告诉我发生了什么事吗?

Could someone please tell me what's happening?

我不知道.

推荐答案

我使用了普通JavaScript(我将其包装在$(function(){})中,因为我最初打算编写jQuery.)因为(至少对我来说),它更容易读取代码(再加上我对jQuery的选择太多,这让我很懒.)

I used plain JavaScript (I wrapped it in a $(function(){}), because I was going to write jQuery initially.)because (at least for me) it's easier to read the code (plus I suck at jQuery too many options makes my mind lazy.)

尽管克隆是实现目标的常用方法,但是还有其他方法可以迭代创建诸如createElement()appendChild();

Although cloning is the common way to accomplish your goal, there are other ways to iterate through the creation of elements such as createElement() and appendChild();

$(function() {
  for (var i = 0; i < 40; i++) {
    var shade = document.getElementById('colors');
    var x = document.createElement('div');
    x.classList.add('x');
    shade.appendChild(x);
  }
});

#colors {
  border: 3px inset black;
  min-height: 30px;
  max-width: 300px;
  display: table;
}
.x {
  border: 1px solid red;
  min-width: 30px;
  border-radius: 50%;
  display: table-cell;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>


<div id="colors">
  <div></div>
</div>

这篇关于不能在for循环中使用多个append()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆