简体   繁体   English

如何从JS文件动态添加字体真棒图标?

[英]How to add font awesome icon dynamically from JS file?

I'm trying to add font awesome icons to my greeting function so in every greeting title a different font awesome icon will be attached. 我正在尝试将字体真棒图标添加到我的问候语功能中,因此在每个问候语标题中将附加一个不同的字体真棒图标。

I tried doing it the traditional way but but javaScript prints the html as text and now the title looks like this: 我尝试以传统方式进行操作,但是javaScript将html打印为文本,现在标题看起来像这样:

Good Morning<i class="fas fa-sun"></i> 

```javascript
function goodSomething() {

  let today = new Date();
  let curHr = today.getHours();

  if (curHr < 12) {
    document.getElementById('greetings').innerText = "Good Morning" + '<i class="fas fa-sun"></i>';
  } else if (curHr < 18) {
    document.getElementById('greetings').innerText = "Good Afternoon" + '<i class="fas fa-coffee"></i>';
  } else {
    document.getElementById('greetings').innerText = "Good Evening" + '<i class="fas fa-moon"></i>';
  }
};

I expect the output of: 我期望输出:

good morning + (sun icon) 早上好+(太阳图标)

good afternoon + (coffee icon) 下午好+(咖啡图标)

good evening + (moon icon) 晚上好+(月亮图标)

You should use innerHTML instead of innerText you want changing html not text of element. 您应该使用innerHTML而不是要更改html而不是元素文本的innerText

<i class="fas fa-sun"></i>  //This is string representing html

Below are two snippets which will show the difference 以下是两个片段,它们将显示差异

Non-Working Code 非工作代码

 document.getElementById("test").innerText = `<i class="fas fa-sun">` 
 <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.8.1/css/all.css" integrity="sha384-50oBUHEmvpQ+1lW4y57PTFmhCaXp0ML5d60M1M7uH2+nqUivzIebhndOJK28anvf" crossorigin="anonymous"> <div id="test"></div> 

Working Code 工作守则

 document.getElementById("test").innerHTML = `<i class="fas fa-sun">` 
 <div id="test"></div> <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.8.1/css/all.css" integrity="sha384-50oBUHEmvpQ+1lW4y57PTFmhCaXp0ML5d60M1M7uH2+nqUivzIebhndOJK28anvf" crossorigin="anonymous"> 

Also you can cleaner and dynamic by using a array of objects. 此外,您还可以通过使用对象数组来清洁和动态化。

function goodSomething() {
  let curHr = new Date().getHours();
  const conds = [
        {cond:curHr < 12, icon:"sun", time:"Morning"},
        {cond:curHr < 18, icon:"coffee", time:"Afternoon"},
        {cond:true, icon:"moon", time:"Evening"}
  ]
  let {time,icon} = conds.find(x => x.cond);
  document.getElementById('greetings').innerHTML = `Good ${time} <i class="fas fa-${icon}"></i>`

};

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

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