使用 jQuery 中的 for 循环创建 div 并为每个 div 分配 ID [英] Create divs using a for loop in jQuery and assign IDs to each div

查看:70
本文介绍了使用 jQuery 中的 for 循环创建 div 并为每个 div 分配 ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在使用 for 循环创建 div.

I am currently creating divs using a for loop.

问题是当我尝试为在 for 循环中创建的每个 div 元素分配一个唯一 ID 时.

The problem is when I try to assign a unique id to every div element that is being created within the for loop.

我越来越近了,但目前计数从 36 开始,而不是 1.

I am getting closer but at the moment the count starts at 36 instead of being 1.

非常感谢您的帮助!

这是我的 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>

现在,这是我的 script.js:

Now, this is my script.js:

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

另外,我的 css:

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

推荐答案

你需要把 loop 放在 side document.ready 而不是把 document.ready 放在 loop 并且你可能不需要增加 i 在循环体中,因为它在循环签名中 increamented .您可以在此处

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. You can read more about document.ready here

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

这篇关于使用 jQuery 中的 for 循环创建 div 并为每个 div 分配 ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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