【问题标题】:How to make a clone of a square in Javascript如何在Javascript中克隆一个正方形
【发布时间】:2019-09-02 13:04:17
【问题描述】:

我有一个网络开发学校的练习,它告诉我:“如何克隆一个正方形 7 次,并将他的数字增加 1(然后从 1 到 8)。

我认为我需要一个“while”循环,递增直到 i = 8,但我不确定。另外,我可以在里面创建一个带有 html 元素的变量,然后尝试复制它吗?

【问题讨论】:

标签: javascript cloning


【解决方案1】:

// create the first square and insert it into doc
const square = document.createElement('div');
square.style.width = '50px';
square.style.height = '50px';
square.style.margin = '10px';
square.style.backgroundColor = 'blue';
square.innerText = 1;

document.body.appendChild(square);

// simple cycle where i begins from needed number
for (let i = 2; i < 9; i++) {
  const clone = square.cloneNode();
  clone.innerText = i;
  document.body.appendChild(clone);
}

【讨论】:

    【解决方案2】:

    希望这将阐明如何选择页面上的元素、使用循环来制作更多元素以及更改每个元素内部的内容。

    // Identifies existing HTML elements so JavaScript can interact with them
    const container = document.getElementById("container");
    const original = document.querySelector(".square");
    
    // Identifies a constant and a variable for our loop
    const total = 8;
    let number = 1;
    
    // Runs a loop as long as the condition is true
    //  (Note: It won't run once number == 8, but the time before that will make square #8)
    while(number < total){
    
      // Changes a value that will effect whether the condition is true
      number++;
      
      // Prints some information about what this iteration of the loop is doing
      console.log("making square number " + number);
    
      // Makes a copy of an HTML element
      const copy = original.cloneNode();
    
      // Changes the copy to be different from the original
      copy.innerHTML = number;
    
      // Adds the copy to the page by appending it to the `container` element
      container.appendChild(copy);  
    }
    .square{
      height: 16px; /* How tall the element will be, not including padding */
      width: 16px;
      padding: 16px; /* How much extra (blue) space the element will include */
      margin: 16px; /* How much extra (white) space the element will have around it */
      font-size: 16px;
      text-align: center
     }
    .blue{
      background-color: lightskyblue;
    }
    <div id="container">
      <div class="blue square">1</div>
    </div>

    【讨论】:

      猜你喜欢
      • 2011-12-19
      • 2018-03-07
      • 1970-01-01
      • 2010-10-18
      相关资源
      最近更新 更多