简体   繁体   English

Javascript 循环:插入元素仅在最后一次迭代中起作用

[英]Javascript Loop: inserting element only working on last iteration

I'm working in Wordpress and trying to add an excerpt to each portfolio card in a grid (there's no way for me to do this via the theme.我在 Wordpress 工作,并试图为网格中的每个投资组合卡添加摘录(我无法通过主题来做到这一点。

Here is the custom script that I am using.这是我正在使用的自定义脚本。 Everything works as expected, except that only the last node in the list gets the excerpt.一切都按预期工作,除了列表中的最后一个节点获得摘录。 I've changed the number of iterations around to test this and it always just inserts the excerpt on the last node that it iterates through.我改变了迭代次数来测试它,它总是只在它迭代的最后一个节点上插入摘录。

Based on this it appears that each new iteration undoes or erases what the prior one did.基于此,似乎每次新的迭代都会撤消或删除前一次所做的。

window.onload = function() {
    const targets = document.querySelectorAll('.entry-header');
    const parent = document.createElement('div');
    const child = document.createElement('p');
    const excerpt = 'This will be the excerpt...';
    
    parent.className = "entry-excerpt";
    parent.appendChild(child);
    child.innerHTML = excerpt;
    
    for (let i = 0; i < targets.length; i++) {
      targets[i].after(parent);
    }
    
  };

I logged targets[i] and each iteration prints correctly我记录了目标 [i] 并且每次迭代都正确打印

You only have one parent element, which visits your entry-header s on the page.您只有一个parent元素,它访问页面上的entry-header

You should try putting everything in the loop.您应该尝试将所有内容都放在循环中。 As I assume the excerpts will be different for each entry, you should create a method to generate them dynamically or fetch them from somewhere.因为我假设每个条目的摘录都会不同,所以您应该创建一个方法来动态生成它们或从某个地方获取它们。

 const targets = document.querySelectorAll('.entry-header'); window.onload = function() { for (let i = 0; i < targets.length; i++) { parent = getExcerpt(i); targets[i].after(parent); } }; function getExcerpt(index) { const parent = document.createElement('div'); const child = document.createElement('p'); const excerpt = 'This will be the excerpt...'; parent.className = "entry-excerpt"; parent.appendChild(child); child.innerHTML = excerpt; return parent; }

Please put the parent inside the loop.请把父级放在循环内。 Checkout the below example查看以下示例

 const targets = document.querySelectorAll('.entry-header'); for (let i = 0; i < targets.length; i++) { const parent = document.createElement('div'); const child = document.createElement('p'); const excerpt = 'This will be the excerpt...'; parent.className = "entry-excerpt"; parent.appendChild(child); child.innerHTML = excerpt; targets[i].after(parent); }
 <div class="entry-header">Entry Header 1</div> <div class="entry-header">Entry Header 2</div> <div class="entry-header">Entry Header 3</div>

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

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