gpt4 book ai didi

javascript - 如何更改javascript dom中访问过的 anchor 链接的颜色

转载 作者:行者123 更新时间:2023-12-03 00:59:34 25 4
gpt4 key购买 nike

我在 Dom 中遇到了问题。我想根据 alreadyRead ( bool 值)更改访问链接的颜色。我是这个领域的新手,所以如果我做错了什么,请原谅我。这是我的代码片段。提前致谢!

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)

最佳答案

最简单的是,您可以通过以下行实现您想要的效果:

aTag.classList.toggle('alreadyRead', book.alreadyRead);

此行使用 Element.classList API 根据开关切换相关 aTag 元素节点上的 alreadyRead 类名称跟在类名后面。如果开关返回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 .

引用文献:

关于javascript - 如何更改javascript dom中访问过的 anchor 链接的颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52682290/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com