[英]For loop append div inside div
Hi I wanted to ask the loop currently in my code I am doing this manually its working manually嗨我想问一下我的代码中当前的循环我正在手动执行此操作它手动工作
$( '<div id="demo1" > <span class="value"></span> </div><br> Loading' ).appendTo( $('.test')[0] );
$( '<div id="demo2"> <span class="value"></span> </div><br> Loading' ).appendTo( $('.test')[1] );
But I am trying to do it buy function until div id demo10 this is what I tried I am trying to implement in for loop but its not working showing blank only can anyone guide me I am new to jquery I will really appreciate any advice.但是我正在尝试购买 function 直到 div id demo10 这是我尝试在 for 循环中实现的尝试,但它不起作用,只有显示空白的人可以指导我我是 jquery 的新手,我将非常感谢任何建议。 Thank you谢谢
function newdiv()
{
var j,i;
for (i = 0; i <= 5; i++,j=i+1) {
$( '<div id="demo-"'+j+'"' +' > <span class="value"></span> </div><br> Loading' ).appendTo( $('.test')[i] );
}
}
I hope the below code will solve the issue我希望下面的代码能解决这个问题
Detail Description详细说明
So when the dom loads we need to execute the function, so we invoked the function using newdiv()所以当dom加载时我们需要执行function,所以我们使用newdiv()调用了function
Now the function gets executed, so each time the i value will get incremented and it will add the new element to the div which is already in html.现在 function 被执行,所以每次 i 值都会增加,它会将新元素添加到已经在 html 中的 div 中。 We select it through class name which is test.我们 select 它通过 class 名称是测试。
So it will append new elements to the test div因此它将 append 新元素添加到测试div
$(document).ready(function() { function newdiv() { var j, i; for (i = 0; i <= 5; i++, j = i + 1) { var appendElement = `<div id='demo-${i}'> <span class='value'></span> </div> <br> Loading`; $('.test').append(appendElement) } } newdiv(); })
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class='test'> hello </div>
Tryout this code, It is giving the same output as well.试用此代码,它也给出相同的 output。
var i=0; for (i = 1; i < 11; i++) { if(i==1) $("#demo").after('<div id="demo1" > <span class="value"></span> </div><br> Loading'); else{ var div = parseInt(i)-1; $("#demo"+div).after('<div id="demo'+parseInt(i)+'" > <span class="value"></span> </div><br> Loading'); } }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="demo" ></div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.