我在这里尝试根据标志值从 head 中删除链接标签。根据标志值,我从 head 中删除链接标签并创建新标签。
在下面的代码中,我只能删除最后一个链接标签,但不能删除 head 标签中的所有链接标签。不确定为什么会这样。
这是我尝试过的。
let bootstrapTheme = true;
let head = document.getElementsByTagName('head')[0],
stylesheets = ['https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.bundle.min.js','https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js']
var link;
stylesheets.forEach(function(stylesheet) {
link = document.createElement('link');
link.rel = 'stylesheet';
link.type = 'text/css';
link.href = stylesheet;
head.appendChild(link);
});
if(!bootstrapTheme){
link.parentNode.removeChild(link);
}
最佳答案
好吧,您可以将创建的所有 link
存储在一个数组中,然后遍历它们并删除它们:
let bootstrapTheme = true;
let head = document.getElementsByTagName('head')[0],
stylesheets = ['https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.bundle.min.js','https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js']
var links = [];
stylesheets.forEach(function(stylesheet) {
var link = document.createElement('link');
link.rel = 'stylesheet';
link.type = 'text/css';
link.href = stylesheet;
head.appendChild(link);
links.push(link);
});
if(!bootstrapTheme){
links.forEach(function(link) {
link.parentNode.removeChild(link);
});
}
但如果我是你,我会简单地将第一个 .forEach()
包装在 if
中,如果不需要则不会添加链接:
let bootstrapTheme = true;
let head = document.getElementsByTagName('head')[0],
stylesheets = ['https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.bundle.min.js','https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js']
if (bootstrapTheme) {
stylesheets.forEach(function(stylesheet) {
var link = document.createElement('link');
link.rel = 'stylesheet';
link.type = 'text/css';
link.href = stylesheet;
head.appendChild(link);
});
}
关于javascript - 如何使用javascript从头部删除链接标签?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60944619/