我想搜索帖子标题中的单词,如果其中包含姓名示例: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/