javascript - forEach in Array (in) 数组 JavaScript

标签 javascript arrays foreach

我想搜索帖子标题中的单词,如果其中包含姓名示例:max 或 Marry,则应添加其中的照片。

    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 测试相同的条件。相同的图像 DOM 元素会被一遍又一遍地修改和添加到前面。变量名称不匹配,标题与标题。 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);
    }
});

关于javascript - forEach in Array (in) 数组 JavaScript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61116985/

相关文章:

javascript - 链接到另一个 html 文件在本地主机上有效,但在我将其上传到服务器时却无效

javascript - 将结构从 C 导出到 wasm?

javascript - 在javascript中动态设置变量

javascript - 相当于 gmaps api 3 中的 getBoundsZoomLevel()

java - 我想向后打印字符串数组元素?

javascript - 获取对象数组中第一个重复项javascript

Javascript 按值在多维数组中搜索?

c++ - C++中的成员函数指针for_each

PHP for 循环与带范围的 foreach

java - 遍历列表时获取 ConcurrentException