
正如上面的图片所描述的,我试图在我的网页中的“一组特定的”访问链接( li标记中的链接)旁边加上一个勾标(✓)。
HTML用于向标签插入一个“”属性。我将这段代码放在页脚(在链接显示在屏幕上之后)。但是,这不起作用(我没有看到在HTML中创建的属性)。
localStorage.setItem('visited-'+window.location.pathname,true);
var links = document.querySelectorAll('#the-content > ul > li > a');
for (i=0;i<links.length;i++) {
var link = links[i];
if (link.host == window.location.host && localStorage.getItem('visited-' + link.pathname + '/')) {
link.dataset.visited=true;
}
}CSS代码
我可以确认这段代码是否正常工作,就好像我手动为标记创建了一个属性一样,应用了样式设置。
article .the-content a[data-visited] {
border-bottom: 1px dashed orange;
}
article .the-content a[data-visited]:after {
content: ' ✓';
}发布于 2021-01-10 05:28:15
link.dataset.visited=true;
link.setAttribute('data-visited', 'true');dataset属性只操作JavaScript属性,但不影响JavaScript属性。有关这种差异的更多信息可以在以下问题中找到:属性和属性在HTML中有什么区别?
发布于 2021-01-10 06:00:56
您可以为此使用createAttribute()
只需替换
link.dataset.visited=true;使用
let attr = document.createAttribute("data-visited"); // Create a "data-visited" attribute
attr.value = true; // Set the value of the attribute
link.setAttributeNode(attr); // assign attribute node to element要了解有关createAttribute() check 这的更多信息,请执行以下操作
更新: html中使用的'the-content‘是一个类,而不是id也替换。
document.querySelectorAll("#the-content > ul > li > a");使用
document.querySelectorAll(".the-content > ul > li > a");https://stackoverflow.com/questions/65650337
复制相似问题