【问题标题】:How do I use querySelector to target a hash at the end of an anchor tag's href attribute?如何使用 querySelector 在锚标记的 href 属性末尾定位哈希?
【发布时间】:2021-05-17 06:57:17
【问题描述】:

我需要使用querySelector 将我的锚标记中的散列定位并匹配到另一个函数,但散列出现在 URL 的末尾。我该怎么做?我正在尝试使用通配符进行匹配,但它不起作用(返回错误Uncaught TypeError: Cannot read property of null)......基本上只需要在哈希之后查询所有内容。感谢您提供任何见解。

<a href="example.abc.org/#xyz">

var newLink = document.querySelector(`[href*='#${id}']`).classList.add('current');

编辑:用美元符号替换以捕捉字符串的结尾,但仍然没有运气......这是上下文的完整代码。我正在尝试创建一个 Intersection Observer。

<a href="example.abc.org/#xyz">

const nav = (entries, observer) => {
      entries.forEach((entry) => {
        if (entry.isIntersecting && entry.intersectionRatio >= 0.55) {
          document.querySelector('li.current').classList.remove('current');
          const id = entry.target.getAttribute('id');
          var newLink = document.querySelector(`[href$='#${id}']`).classList.add('current');
        }
      });
    }
    const options = {
      root: null
    };
const observer = new IntersectionObserver(nav,options);
    // target the elements to be observed
    const sections = document.querySelectorAll('section.op-section');
    sections.forEach((section) => {observer.observe(section);});

【问题讨论】:

  • 试试&lt;a href="example.abc.org/#xyz"&gt;href 周围缺少引号)。
  • 谢谢,但这只是一个例子——实际的锚点是在后端生成的。为了清楚起见,我会修正。

标签: javascript jquery jquery-selectors queryselector


【解决方案1】:

刚刚看到我的错误:current 类附加到列表项而不是锚点。谢谢。

【讨论】:

    猜你喜欢
    • 2011-12-28
    • 2015-05-09
    • 2017-10-14
    • 2021-09-23
    • 1970-01-01
    • 2019-11-23
    • 1970-01-01
    • 2012-06-08
    • 2013-12-29
    相关资源
    最近更新 更多