如何在Java脚本dom中更改已访问锚链接的颜色

时间:2018-10-06 18:47:57

标签: javascript jquery dom

我在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)

1 个答案:

答案 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>

JS Fiddle demo

参考文献: