簡體   English   中英

forEach in Array (in) 數組 JavaScript

[英]forEach in Array (in) Array JavaScript

我想在我的帖子的標題中搜索單詞,如果它包含名稱示例: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");
      }
    })

它有效,但我在 class 中有很多標題,它只在 class 的最后一個元素中添加了圖片。

有幾行看起來不正確。 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);
    }
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM