我正在尝试将字体真棒图标添加到我的问候函数中 因此在每个问候语标题中都会附加一个不同的字体真棒图标。
我尝试以传统方式进行操作,但是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>';
}
};
我希望输出:
早上好+(太阳图标)
下午好+(咖啡图标)
晚上好+(月亮图标)
答案 0 :(得分:0)
您应该使用innerHTML
而不是innerText
来更改html而不是元素文本。
<i class="fas fa-sun"></i> //This is string representing html
下面是两个片段,它们将显示差异
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>
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">
此外,您还可以通过使用一系列对象来实现清洁和动态化。
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>`
};