javascript - 在 vanilla JS 中重写所有以特定 ID 开头的 <a> 对象的 href

标签 javascript

我正在尝试使用 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/

相关文章:

javascript - Vue 组件 Props 仅在 $vnode 上可用

javascript - 当div到达页面一定高度时

javascript - Jquery全局变量赋值和在javascript函数中的使用

javascript - css链接的ease-in和ease-out是怎么定义的?

javascript - 如何使用 Angular 禁用 CSS anchor ?

javascript - 混合ajax和完整请求

javascript - jQuery wrap 和 appendTo 不会导致预期的结果

Javascript 适用于除 Chrome 之外的所有浏览器

javascript - 如何在 React 中将所有数组项重新排序到特定索引?

javascript - 无法获取 HTML ANCHOR + 如何覆盖 anchor 的 .onclick