我想使用HTML ' base‘元素来更改我的基目录。但我只想为我的'a‘元素更改基目录,而不是我的脚本和样式包含。
所以我发现我可以使用基本元素,但我想我不能再做更多的修改了。
<base href="https://example.com/">
//Don't change root for this:
<script src="../js/example.js"></script>
//Only change root for this:
<a href="../example">example</a>有人知道我该怎么做吗?也许是javascript或者别的什么。但是我找不到任何关于这个的东西。
我得到了类似这样的东西:(不工作)
$('a').each(function() {
var value = $(this).attr('href');
$(this).attr('href', 'new/root/' + value);
});发布于 2019-01-27 02:52:55
欢迎使用StackOverflow。要做到这一点,最简单的方法是使用querySelectorAll获取所有锚标记。一旦你抓取了所有的元素,我们就可以使用forEach用一个函数来迭代每个锚标记。
该函数将使用getAttribute获取href属性。有了href之后,我们使用replace运行一个快速的正则表达式,该表达式查找所有的点和斜杠,并将它们替换为空字符。现在我们删除了这些字符,我们可以使用setAttribute重新分配href。
const allAnchorTags = document.querySelectorAll('a');
allAnchorTags.forEach(function(anchorTag) {
var href = anchorTag.getAttribute('href');
var splitHref = href.replace(/\.|\//g, '');
anchorTag.setAttribute('href', '/'+splitHref);
});有关示例中使用的方法列表,请参阅以下内容:
查询选择器All:https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll
获取属性:https://developer.mozilla.org/en-US/docs/Web/API/Element/getAttribute
设置属性:https://developer.mozilla.org/en-US/docs/Web/API/Element/getAttribute
替换:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace
https://stackoverflow.com/questions/54381502
复制相似问题