如何在jQuery中使用“追加”创建多个DIV?

时间:2019-02-14 16:30:50

标签: javascript for-loop append

我想循环多个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}}
]

1 个答案:

答案 0 :(得分: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>