繁体   English   中英

select id 包含带有 querySelectorAll 的斜线不起作用

[英]select id contain slash with querySelectorAll is not working

<h2 id="example/123">A heading</h2>

<script>
document.querySelectorAll("#example/123");
</script>

知道为什么上面的 id 不起作用吗? 我需要额外的库来转义/吗?

您可以使用\\转义 /。

<h2 id="example/123">A heading</h2>

<script>
document.querySelectorAll("#example\\/123");
</script>

重复CSS 选择器以选择 ID 名称中带有斜杠的 ID?

但是,在这种情况下,您使用的是 id,因此您可以获取特定元素,而无需使用 document.getElementById() 从 NodeList 中获取它,因为只有一个元素应该具有该 id。

document.getElementById("hello/world");

好吧,有时新手在学习 JS 时,他们会错误地将两个 HTML 标签之间的 Javascript 链接链接起来。 所以他们编码你在 Js 中选择一个特定的 HTML 元素并且不会选择 HTML 标签。

流行的解决方案:

在 HTML 标签之间链接你的 JS :)

 let para = document.querySelectorAll('h1'); para.forEach((allpara) => { console.log(allpara) });
 <,DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width. initial-scale=1.0" /> <title>JavaScript Learning Project</title> </head> <body> <h1> This is 1st </h1> <h1> This is 2nd </h1> <h1> This is 3rd </h1> <h1> This is 4th </h1> <script src="index.js"></script> </body> </html>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM