简体   繁体   English

对于循环内部我的自定义功能不起作用

[英]For loop inside my custom function doesn't work

I'm trying to create a function that uses the number input I got from users to create the same amount of division inside of a container division.However, no matter what the number is, it always creates only 1 div. 我正在尝试创建一个函数,它使用我从用户那里得到的数字输入来在容器分区内创建相同数量的除法。但是,无论数字是多少,它总是只创建1个div。 It seems like the for loop inside my function is being avoided. 看起来我的函数中的for循环似乎正在被避免。

I've tried to alter the function, checked number input whether it is defined or undefined. 我试图改变函数,检查数字输入是否已定义或未定义。

function createGrid(parameter) {
  for (i = 0; i < parameter * parameter; i++); {
    const div = document.createElement('div');
    newDiv = container.appendChild(div);
    newDiv.setAttribute('class', 'newDiv');
  }
  return newDiv;
}

You have semicolon ; 你有分号; after for loop which is essentially an empty statement. for循环之后for这实际上是一个空语句。

That is the reason the for loop is not working as expected, and rest of your code is just creating one divider. 这就是for循环没有按预期工作的原因,你的代码的其余部分只是创建一个分隔符。

Remove the semicolon ; 删除分号; to fix the issue. 解决问题。

Additional to Nikhil's answer, here is how I would write it (without using global variables, which is considered to be bad practice in most cases): 除了Nikhil的答案之外,这里是我如何编写它(不使用全局变量,在大多数情况下这被认为是不好的做法):

function createGrid(parameter) {
  let newDiv;
  for (let i = 0; i < parameter * parameter; i++) {
    newDiv = document.createElement('div');
    newDiv.setAttribute('class', 'newDiv');
    container.appendChild(newDiv);
  }
  return newDiv;
}

If you don't need to return the last div added, just remove the let newDiv; 如果您不需要返回添加的最后一个div,只需删除let newDiv; line and put the const keyword back into the first line of the for loop. line并将const关键字放回for循环的第一行。 Also remove the return value then. 同时删除返回值。

function createGrid(parameter) {
  for (let i = 0; i < parameter * parameter; i++) {
    const newDiv = document.createElement('div');
    newDiv.setAttribute('class', 'newDiv');
    container.appendChild(newDiv);
  }
}

It is because you have to declare the variable "i", try this: 这是因为你必须声明变量“i”,试试这个:

function createGrid(parameter){
  for(let i = 0 ; i < parameter*parameter; i++);{
    const div = document.createElement('div');
    newDiv = container.appendChild(div);
    newDiv.setAttribute('class','newDiv');}
  return newDiv;
}

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

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