簡體   English   中英

我如何在 javascript 中使用 jquery 循環 html 元素?

[英]How can i loop html element using jquery in javascript?

我想使用 jquery 在左列 div 中重復“發布”div 及其所有內容,例如 50 次,並在 html 中調用它?

HTML:

 <div class="post"> Content </div>

記者:

var jQueryScript = document.createElement('script');
jQueryScript.setAttribute('src', 'https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js');
document.head.appendChild(jQueryScript);

$(document).ready(function(i) {
for (let i = 2; i < 100; i++) {
  $(".post:eq(0)").clone().appendTo(".left-col");
}


 });

你可以這樣做:

$(document).ready(function(i) {
  for (let i = 0; i < 50; i++) {
    $(".post:eq(0)").clone().appendTo("#left-col");
  }
});

您的代碼存在一些問題。 首先$("#post")應該是$(".post") ,因為它是 class 而不是 id。

其次,您的for循環不正確。 你錯過了{}而且它應該是i < 50而不是i < i.length(50)

同樣重要的是要注意我已經添加了:eq(0)$(".post") ,因為如果沒有它會導致一個大問題。 因為循環第一次運行時,您將有 1 個元素與 class post ,第二次您將有 3 個元素,第三次 = 6 個元素,到目前為止。

 $(document).ready(function(i) { for (let i = 0; i < 50; i++) { $(".post:eq(0)").clone().appendTo("#left-col"); } });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="post"> Content </div> <div id="left-col"></div>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM