我在Dom遇到问题。我想基于alreadyRead
(布尔值)更改访问链接的颜色。我是这个领域的新手,所以如果我做错了任何事情,请原谅我。这是我的代码段。预先感谢!
var books = [
{
title: 'The Design of EveryDay Things',
author: 'Don Norman',
alreadyRead: false
},
{
title: 'The Most Human Human',
author: 'Brian Christian',
alreadyRead: true
}
];
var appHandle = document.getElementById('app');
var ulTag = document.createElement('ul')
books.forEach(book =>{
if(book.alreadyRead === true){
document.linkcolor="green"
} else{
document.linkcolor ="red"
}
var liTag = document.createElement('li');
var navList =document.createTextNode(`${book.title} by ${ book.author}`)
var aTag = document.createElement('a')
aTag.setAttribute('href','#');
aTag.appendChild(navList)
liTag.appendChild(aTag);
ulTag.appendChild(liTag);
})
appHandle.appendChild(ulTag)
答案 0 :(得分:1)
最简单的方法是,通过以下几行代码可以实现您想要的目标:
aTag.classList.toggle('alreadyRead', book.alreadyRead);
此行使用Element.classList
API,根据跟在类名后面的开关,在相关alreadyRead
元素节点上切换aTag
类名。如果开关返回true
,则添加类(如果尚不存在),或者如果开关返回false
,则删除类名(如果存在)。
var books = [{
title: 'The Design of EveryDay Things',
author: 'Don Norman',
alreadyRead: false
},
{
title: 'The Most Human Human',
author: 'Brian Christian',
alreadyRead: true
}
];
var appHandle = document.getElementById('app');
var ulTag = document.createElement('ul')
books.forEach(book => {
var liTag = document.createElement('li');
var navList = document.createTextNode(`${book.title} by ${ book.author}`);
var aTag = document.createElement('a')
aTag.setAttribute('href', '#');
aTag.appendChild(navList)
liTag.appendChild(aTag);
ulTag.appendChild(liTag);
aTag.classList.toggle('alreadyRead', book.alreadyRead);
})
appHandle.appendChild(ulTag)
.alreadyRead {
color: limegreen;
}
<div id="app"></div>
参考文献: