javascript - 使用 javascript 创建多个元素

标签 javascript ajax createelement

我有一个 html 元素树示例(如下),我想返回数据库中每个匹配项的相关数据。假设有 5 个匹配项。 我是否需要创建 5 个给定元素并用 JavaScript 数据填充它们?

我要运行一个循环,但这看起来会降低性能(为每次匹配创建所有元素树)。相反,我可以使用给定的元素(pic)用javascript填充它并将其放到dom上(x次)吗?如果可以的话怎么办?

<!-- sample elem -->
<div class="col-12 col-md-4" style="display: none">
    <div class="card my-3 mx-1">
        <a href="#"><img src="" alt="img"></a>
        <div class="card-body">
            <div class="row">
                <div class="col-12 p-1">Country</div>
                <div class="col-3 p-1">State</div>
                <div class="col-4 p-1">City</div>
            </div>
        </div>
    </div>
</div>

最佳答案

进一步阐述我的评论:通常是向 DOM 树中重复插入元素会导致性能问题,因为每次插入新节点时文档都需要重排。您不应该担心调用/调用 document.createElement() 太多次:这是您最不需要担心的。

因此,我建议您使用函数来创建整个示例元素。然后,您可以在循环的每次迭代中调用此函数来创建整个卡片元素,然后将其附加到文档片段中。

伪代码:

function createCard() {
  // Create the entire `sample element` as you would call it
  const el = <something>;
  return el;
}

// Create new document fragment to hold all the nodes
// At this point, we are NOT injecting them into the DOM yet
const fragment = new DocumentFragment();

// Go through your data and create new card for each data point
for (let i = 0; i < 5; i++) {
    fragment.appendChild(createCard());
}

// Now this is when you insert the entire bulk of the content into the DOM
document.querySelector('#myInsertionTarget').appendChild(fragment);

概念验证代码如下:

// Since we are creating so many `<div>` elements
// It helps to further abstract its logic into another function
function createDivElement(classes, text) {
  const div = document.createElement('div');
  
  if (classes.length)
    div.classList.add(...classes);
  
  if (text)
    div.innerText = text;
  
  return div;
}

// Call this whenever you want to create a new card
function createCard(i) {
  const colCountry = createDivElement(['col-12', 'p-1'], 'Country');
  const colState = createDivElement(['col-3', 'p-1'], 'State');
  const colCity = createDivElement(['col-4', 'p-1'], 'City');
  
  const row = createDivElement(['row']);
  row.appendChild(colCountry);
  row.appendChild(colState);
  row.appendChild(colCity);
  
  const cardBody = createDivElement(['card-body']);
  cardBody.appendChild(row);
  
  const image = document.createElement('img');
  image.alt = 'img';
  // Proof-of-concept image source, you can ignore this!
  image.src = `https://placehold.it/100x50?text=Image%20${i+1}`;
  
  const imageLink = document.createElement('a');
  imageLink.href = '#';
  imageLink.appendChild(image);
  
  const card = createDivElement(['card', 'my-3', 'mx-1']);
  card.appendChild(imageLink);
  card.appendChild(cardBody);
  
  const outer = createDivElement(['col-12', 'col-md-4']);
  // outer.style.display = 'none';
  outer.appendChild(card);
  
  return outer;
}

// Create new document fragment
const fragment = new DocumentFragment();

// In each iteration of the loop, insert the new card element into fragment
for (let i = 0; i < 5; i++) {
  const el = createCard(i);
  fragment.appendChild(el);
}

// When you're done generating the entire set of elements
// You can then insert the fragment into your DOM (finally!)
document.querySelector('#app').appendChild(fragment);
<div id="app"></div>

关于javascript - 使用 javascript 创建多个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60697428/

相关文章:

php - 使用 PHP DOMDocument 将样式标签添加到头部

javascript - 如何使不同屏幕尺寸的 div 居中?

javascript - 在移动设备上查看固定标题

javascript - 提交表单后保留下拉菜单的 $_GET 值

asp.net - 在 IE 7 中调用 Ajax 后,CSS 样式消失了

javascript - 发送XMLHttpRequest并且信息服务器不发送任何确认

javascript - 使用javascript自动开始打印html页面

javascript - jQuery 动态 DOM 创建性能

JavaScript:将对象属性附加为子元素

javascript - 表格、tr、td 标签上的 document.createElement IE8 失败