数组中的forEach(in)数组JavaScript

数组中的forEach(in)数组JavaScript,javascript,arrays,foreach,Javascript,Arrays,Foreach,我想在我的帖子的标题中搜索单词,如果它包含名字,例如:max或Mary,它应该添加他们的照片 var imageLocation = document.querySelectorAll(".summary"); // where Image should be added var headLines = document.querySelectorAll(".ecs-thumbnail");// where my Names are. var img = document

我想在我的帖子的标题中搜索单词,如果它包含名字,例如:max或Mary,它应该添加他们的照片

    var imageLocation = document.querySelectorAll(".summary"); // where Image should be added
    var headLines = document.querySelectorAll(".ecs-thumbnail");// where my Names are.
    var img = document.createElement("IMG");

   headlines.forEach(function (pos){
      const txt = pos.innerText;
      var max = txt.includes("max");
      var marry = txt.includes("marry");

    if(marry === true){
    pos.parentNode.childNodes[1].prepend(img);
    img.setAttribute("src", "https://dev.musikzentrum-hannover.de/wp-content/uploads/marry.png");
      } else if(max === true){
      pos.parentNode.childNodes[1].prepend(imgAus);
    img.setAttribute("src", "https://dev.musikzentrum-hannover.de/wp-content/uploads/max.png");
      }
    })

它是有效的,但我在课堂上有很多标题,它只在课堂的最后一个元素中添加了图片。

有几行看起来不对劲。相同条件下的if/else if测试。同一个imagedom元素被反复修改和添加前缀。变量名不匹配,标题与标题。imageLocation从未使用过。这可能会奏效:

var headLines = document.querySelectorAll(".ecs-thumbnail");// where my Names are.

headLines.forEach(function (pos){
    let src;
    if(pos.innerText.includes("marry")){
        src = "https://dev.musikzentrum-hannover.de/wp-content/uploads/marry.png";
    } else if(pos.innerText.includes("max")) {
        src = "https://dev.musikzentrum-hannover.de/wp-content/uploads/max.png";
    }

    if(src) {
        let img = document.createElement("IMG");
        img.setAttribute("src", src);
        pos.parentNode.childNodes[1].prepend(img);
    }
});

我不太清楚你的意思。不知道为什么要使用innerText来获得一个值并决定它。请尝试重新表述你的问题。我刚刚编辑了我的文本。对不起;)如果声明不正确,请提前感谢。if和else if针对相同条件进行测试,因此后者将永远不会执行;另外,您正在反复覆盖最后插入的img DOM元素并不断添加它。我不确定您的问题是否正确。但很可能需要将图像创建移动到iteratee函数<代码>var img=document.createElement(“img”)”。@TheCollal,您有什么建议?