简体   繁体   English

为js中的每个数据附加div

[英]append div for each data in js

I'm using AJAX to append data to div element.我正在使用 AJAX 将数据附加到 div 元素。 The div class item style display is none because the div class only appear when the success function works.basically the div class dependent on the success function. div类样式显示为none,因为div类只有在success函数起作用时才会出现。基本上就是div类依赖于success函数。

<div class="item" style="display: none;">
<div class="Name"></div> //here I want to show the success function data
<select class="price">
 <option>A</option>
 <option>B</option>
 <option>C</option></select>
</div>

div only shows when it finds data. div 仅在找到数据时显示。 I want to add data in div class="Name" and append each data.我想在div class="Name" 中添加数据并附加每个数据。 like when first data is added then the item div will show and when the 2nd data is added then 2nd data will be shown.就像添加第一个数据时,项目div 将显示,当添加第二个数据时,将显示第二个数据。 for each data div class item , Name , price will appear.对于每个数据 div 类itemNameprice将出现。 In this code data only appending in the same div.在此代码中,数据仅附加在同一个 div 中。

success:function(data) {
console.log(data);
$('.item').show();
$('.Name').append(data);}

How can i do this?我怎样才能做到这一点?

Having a parent container有一个父容器

<div class="items">
</div>

You can use append to create new "item" elements inside this container using append您可以使用 append在此容器内使用 append 创建新的“项目”元素

// create inner element
var newItem=$('<div class="item"></div>');
// inserting data
newItem.html(data);
// append to parent container
 $('.items').append(newItem);

So, the very simple answer here is your in-line styling.因此,这里非常简单的答案是您的内嵌样式。 If you look at the code, you have written display: none;如果你看代码,你写的是display: none; . . This tells the rendering engine to hide it from the current object model.这告诉渲染引擎将它从当前对象模型中隐藏起来。

However, when the success function runs, it executes .show() which disables display: none;但是,当success函数运行时,它会执行.show()禁用display: none; . .

To fix this,为了解决这个问题,

<div class="items" style="display: none;"></div>

Then you can store that as a literal and dynamically add content using mapping like so:然后您可以将其存储为文字并使用映射动态添加内容,如下所示:

$( '.items' ).show();
const dataHtml = '<div class="item">' + data + '</div>';
$( '.items' ).append( dataHtml );

PS: You can check it out here . PS:你可以在这里查看

you can use this to append new div of items.您可以使用它来附加项目的新 div。 you need to add item container which is the div with id all_items您需要添加项目容器,它是 ID 为all_items的 div

<div id="all_items"></div>

success:function(data) {
console.log(data);
$('#all_items').append('<div class="item">+data+</div>');
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM