简体   繁体   English

如何根据另一个文本更改图标

[英]How to change icon based on another text

Basically, I want my webpage to show a specific icon (using fontawesome) if the title includes a specific word, right now, it works if I include just that one word in the title, but if I include more words, then it doesn't recognize it.基本上,如果标题包含特定单词,我希望我的网页显示特定图标(使用 fontawesome),现在,如果我只在标题中包含那个单词,它就可以工作,但是如果我包含更多单词,则它不会不认识它。

I am fairly new to Js, at first, it didn't work at all, but then I separated the two classes "fas" and "fa-eye" and now they work properly if you add each separately.我对 Js 相当陌生,起初,它根本不起作用,但后来我将两个类“fas”和“fa-eye”分开,现在如果单独添加它们,它们可以正常工作。

var icon = document.getElementsByClassName("postTitleIcon");
var text = document.getElementsByClassName("postTitle");
for(var i = 0; i < icon.length; i++) {
    if(text[i].textContent == "eye") {
        icon[i].classList.add("far");
        icon[i].classList.add("fa-eye");
    }
}

I expect the icon to show if the word "eye" is in the HTML, no matter what comes before or after it.我希望图标显示“眼睛”这个词是否在 HTML 中,无论它之前还是之后。

Alright, everyone, I think I found the answer, you simply need to add includes after textContent .好吧,大家,我想我找到了答案,你只需要在textContent之后添加includes

here's the code now, I tried a couple of times and it seems like it works like I wanted to:这是现在的代码,我尝试了几次,似乎它像我想要的那样工作:

var icon = document.getElementsByClassName("postTitleIcon");
var text = document.getElementsByClassName("postTitle");
for(var i = 0; i < icon.length; i++) {
    if(text[i].textContent.includes("eye")) {
        icon[i].classList.add("far");
        icon[i].classList.add("fa-eye");
    }
}

Thanks to Sebastian for pointing it out.谢塞巴斯蒂安指出这一点。

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

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