简体   繁体   English

根据变量显示多个 div

[英]Show a number of divs depending on a variable

How I can print N divs (each div represent a dot) dynamically?如何动态打印 N 个 div(每个 div 代表一个点)? I am new in HTML and CSS, is there a way to print N divs depending on a variable.我是 HTML 和 CSS 的新手,有没有办法根据变量打印 N 个 div。 Do I need a Jquery function?我需要 Jquery function 吗?

 .dot-container { display: inline-block; }.dot{ width:10px;important: height;10px:important; border-radius: 50%; display. inline-block: };red{ background-color. red:important; }.blue{ background-color: blue;important; } .yellow{ background-color: yellow !important; }
 <div class="dot-container"> <div class="dot red"></div> <div class="dot blue"></div> <div class="dot yellow"></div> <div class="dot red"></div> </div>

Thats my code: https://jsfiddle.net/bpc8shra/那是我的代码: https://jsfiddle.net/bpc8shra/

You can do it with JS.你可以用 JS 来做。 Enter a number and click create button:输入一个数字并单击创建按钮:

 let button = document.getElementById("button"), number = document.getElementById("number"), ctn = document.getElementById("dot-container") // Just a function to add random colors, getRandomColor = function() { var hex = Math.floor(Math.random() * 0xFFFFFF); return "#" + ("000000" + hex.toString(16)).substr(-6); } button.addEventListener("click", () => { for(let i = 0; i < Number(number.value); i++){ let dot = document.createElement("div"); dot.classList.add("dot") dot.style.backgroundColor = getRandomColor(); ctn.appendChild(dot) } })
 .dot { width: 10px;important: height; 10px:important; border-radius: 50%; display: inline-block; margin-right: 5px; }
 <input type="number" id="number" /> <button id="button">Create</button><br/><br/> <div id="dot-container"> </div>

I hope I understood you correctly, YOU mean something like this:我希望我理解正确,你的意思是这样的:

var red_dots = 15
for (var i=0; i<red_dots;i++)
  $('.dot-container').append('<div class="dot red"></div>');

https://jsfiddle.net/9sh7bm21/ https://jsfiddle.net/9sh7bm21/

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

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