如何在jQuery中使用'append'创建多个DIV?

问题描述 投票:0回答:1

我想循环多个DIV元素。

有5本书。我想在ID:BootLoop中循环出5本书。

我尝试了什么?

my_orders.append(data[i].order.bname).appendTo("#bookLoop > div > div > div > h3");

my_orders.append(data[i].order.blink).appendTo("#bookLoop > div > div > div > a");

它没用。我哪里弄错了?

JS:

var my_orders = $("#bookLoop"); 
$.each(data, function(i, order) {
     $("#bookName").append(data[i].order.bname);,
     $("#bookURL").append(data[i].order.blink);
});

HTML(应循环的代码结构):

<div id="bookLoop">
   <div class="col-3">
      <div class="block-content">
        <div class="d-md-flex">
            <h3 id="bookName" class="h4 font-w700"></h3>
        <div>
        <div class="d-md-flex link">
           <a href="#" id="bookURL">Details</a>
        <div>
      <div>
   <div>
<div>

JSON:

[
   {"order":{"id":"61","bname":"Book 1","blink":984}},
   {"order":{"id":"42","bname":"Book 2","blink":5414}},
   {"order":{"id":"185","bname":"Book 3","blink":4521}},
   {"order":{"id":"62","bname":"Book 4","blink":41254}},
   {"order":{"id":"15","bname":"Book 5","blink":7464}}
]
javascript for-loop append
1个回答
0
投票

我认为你想要的是在#bookLoop中附加每本书和链接,签署每本书并链接它自己的内容。

下面我为每本书创建元素(节点),然后将其附加到my_orders

看看它是否是您想要的,如果没有,请编辑您的问题,显示所需渲染HTML的示例

var my_orders = $("#bookLoop"); 
var books = ''
var links = ''

let data = [
   {"order":{"id":"61","bname":"Book 1","blink":984}},
   {"order":{"id":"42","bname":"Book 2","blink":5414}},
   {"order":{"id":"185","bname":"Book 3","blink":4521}},
   {"order":{"id":"62","bname":"Book 4","blink":41254}},
   {"order":{"id":"15","bname":"Book 5","blink":7464}}
]

$.each(data, function(i, order) {
  let col = document.createElement('div')
  col.className = 'col-3'
  
  let content = document.createElement('div')
  content.className = 'block-content'
  
  let flexC = document.createElement('div')
  flexC.className = 'd-md-flex'
  
  let title = document.createElement('h3')
  title.className = 'h4 font-w700'
  title.textContent = data[i].order.bname;
  flexC.append(title)
  
  let flexL = document.createElement('div')
  flexL.className = 'd-md-flex link'
  
  let details = document.createElement('a')
  details.className = 'bookURL'
  details.href = "#"
  details.textContent = "Details: " + data[i].order.blink
  flexL.append(details)
  
  my_orders.append(col)
  col.append(content)
  content.append(flexC)
  content.append(flexL)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="bookLoop">   
<div>
© www.soinside.com 2019 - 2024. All rights reserved.