我一定是想多了。我需要选择所有具有类名 cbs-Line1Link
的 anchor 标记,如果它与文件类型(ppt、pptx、doc、docx 等)匹配,则添加 ?Web=1
到 HREF 的末尾。所以,ppt
变成了 pptx?Web=1
<a class="cbs-Line1Link" href="index.pptx">pptx title</a>
--------------------------------------------------------
const items = document.querySelectorAll(".cbs-Line1Link");
items.forEach(item => {
let href = item.getAttribute("href")
if (href.substring(href.length - 5) == '.pptx') {
console.log(item)
return item = item.getAttribute("href").replace(/\bpptx\b/, 'pptx?Web=1')
}
})
提前致谢!
最佳答案
只需在您的条件中设置href
。你不需要返回任何东西。示例:
const items = document.querySelectorAll(".cbs-Line1Link");
items.forEach(item => {
let href = item.getAttribute("href");
if (href.substring(href.length - 5) == '.pptx') {
console.log(item);
item.href = href + '?Web=1';
}
})
<a class="cbs-Line1Link" href="index.pptx">pptx title</a>
更好的是,由于您的扩展名的长度可能不同,您可以做这样的事情来更容易地匹配所有的扩展名:
const items = document.querySelectorAll(".cbs-Line1Link");
items.forEach(item => {
const href = item.getAttribute("href");
const extension = href.substring(href.lastIndexOf(".") + 1);
if (['ppt', 'pptx', 'doc', 'docx'].includes(extension)) {
console.log(item);
item.href = href + '?Web=1';
}
})
<a class="cbs-Line1Link" href="index.pptx">pptx title</a>
关于javascript - 在 Javascript 中替换/附加 HREF 文件类型扩展名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59524237/