【发布时间】: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);});
【问题讨论】:
-
试试
<a href="example.abc.org/#xyz">(href周围缺少引号)。 -
谢谢,但这只是一个例子——实际的锚点是在后端生成的。为了清楚起见,我会修正。
标签: javascript jquery jquery-selectors queryselector