我正在尝试使用 vanilla JS(无 jQuery 等)将参数附加到菜单中多个项目的 URL。
我想要使用的所有菜单项都有一个共同点,我认为这是选择正确对象的关键:它们都以相同的 ID 开头。
所以我所拥有的看起来像这样:
<a href="someplace.php" id="actionMenu123">Link 1</a>
<a href="someplace2.php" id="actionMenu456">Link 2</a>
<a href="someplace3.php" id="actionMenu789">Link 3</a>
<a href="someplace4.php" id="actionMenuABV">Link 4</a>
<a href="someplace5.php" id="actionMenu5X4">Link 5</a>
我需要的 JS 脚本应该产生以下结果:
<a href="someplace.php?John=Doe" id="actionMenu123">Link 1</a>
<a href="someplace2.php?John=Doe" id="actionMenu456">Link 2</a>
<a href="someplace3.php?John=Doe" id="actionMenu789">Link 3</a>
<a href="someplace4.php?John=Doe" id="actionMenuABV">Link 4</a>
<a href="someplace5.php?John=Doe" id="actionMenu5X4">Link 5</a>
我尝试使用 querySelectorAll 选择 DOM 中包含“actionMenu”的所有 <a>
对象来重写 href,但我认为我做得不对。
如果有任何指点,我将不胜感激。
最佳答案
// first, get list of all 'a' tags and convert to array
[].slice.call(document.querySelectorAll('a'))
// filter for ones whose id matches. We also want to make
// sure it *has* an id and an href
.filter(node => node.id && node.href && node.id.match(/^actionmenu/i))
// rewrite the href
.forEach(node => node.href = node.href + '?John=Doe');
关于javascript - 在 vanilla JS 中重写所有以特定 ID 开头的 <a> 对象的 href,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40405122/