简体   繁体   English

在jQuery中使用for循环创建div并为每个div分配ID

[英]Create divs using a for loop in jQuery and assign IDs to each div

I am currently creating divs using a for loop. 我目前正在使用for循环创建div。

The problem is when I try to assign a unique id to every div element that is being created within the for loop. 问题是当我尝试为在for循环中创建的每个div元素分配唯一的id时。

I am getting closer but at the moment the count starts at 36 instead of being 1. 我越来越近,但目前计数从36开始而不是1。

Thanks so much for you help! 非常感谢你的帮助!

Here is my html: 这是我的HTML:

<!DOCTYPE html>
<html>
<head>
<title>Intro Webpage!</title>

<meta charset="UTF-8" /> 
<meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.0; user-scalable=0; target-densitydpi=device-dpi" />
<link rel="stylesheet" type="text/css" href="style.css"/>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="script.js"></script>
</head>
<body>
</body>
</html>

Now, this is my script.js: 现在,这是我的script.js:

for(i = 0; i < 35; i++) {
$(document).ready(function(){
    $('body').append('<div id="div'+ (i++) +'" />');
});
}

Also, my css: 另外,我的css:

div {
width: 167px;
height: 167px;
border-radius: 10px;
background-color: #ff0000;
display: inline-block;
margin-left: 5px;
}

You need to put loop in side document.ready instead of putting document.ready in loop also you may not need to increament i within loop body as it is increamented in loop signature. 你需要把loop in side document.ready instead of putting document.ready in loop你也可能不需要increament i循环体内,因为它是increamented在环签名。 You can read more about document.ready here 您可以在此处阅读有关document.ready的更多信息

$(document).ready(function(){
  for(i = 0; i < 35; i++) {
    $('body').append('<div id="div'+ i +'" />');
  }
});

All the provided answers will do the job but if you want to make it faster, you can do it like this. 所有提供的答案都可以完成,但如果你想让它更快,你可以这样做。 Also, if you want the div id to start with 1, you should do ++i instead of i++ . 另外,如果你想让div id以1开头,你应该做++i而不是i++ i++ doesn't make sense since that's being done by the for loop automatically. i++没有意义,因为这是由for loop自动完成的。

$(document).ready(function() {
    var divsToAppend = "";
    for (i = 0; i < 35; i++) {
        divsToAppend += '<div id="div' + (++i) + '" />';        
    }
    $('body').append(divsToAppend);
});​​

Try: 尝试:

$(document).ready(function(){
    var html='';
    for(i = 0; i < 35; i++) {
        html += '<div id="div'+ i +'" />';
    }
    $('body').append(html);
});

Take the $(document).ready out of the loop for starters. 将$(document).ready从循环中取出来作为初学者。

$(document).ready(function() {
    // do loop here
}    

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

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