javascript - 选择器抛出 DOMException 但在控制台中工作 - Tailwind 类选择器
问题描述
我正在使用 Tailwind CSS 和 vanilla JS,我正在尝试通过内置选择器获取一些特定节点。问题:当浏览器执行的代码(捆绑在 Webpack 中)时,选择器被标记为无效,但我可以让它在 Web 控制台中工作。
这是一个可复制的样本;问题似乎在于w-2/4
包含 a/
所以我正在逃避它以使其像\\/
. 采取任何想法来解决这个问题......
const prefix = '.';
const width = 'w-2/4';
const rounded = 'rounded';
const selector = prefix + width + prefix + rounded;
parsed = selector.replace('/', '\\\\/');
console.log(parsed);
const matches = document.querySelectorAll('.w-2\\/4.rounded');
console.log(matches);
const broken = document.querySelectorAll(parsed);
console.log(broken);
<h3 class="inline-block statlib-kpi-value text-2xl h-4 bg-blue-400 rounded w-2/4 "></h3>
由@biberman 回答,感谢他。
解决方案
我认为问题在于这里有 4 个反斜杠parsed = selector.replace('/', '\\\\/');
,应该只有两个 ...
工作示例:
const prefix = '.';
const width = 'w-2/4';
const rounded = 'rounded';
const selector = prefix + width + prefix + rounded;
parsed = selector.replace('/', '\\/');
console.log(parsed);
const matches = document.querySelectorAll('.w-2\\/4.rounded');
console.log(matches);
const broken = document.querySelectorAll(parsed);
console.log(broken);
<h3 class="inline-block statlib-kpi-value text-2xl h-4 bg-blue-400 rounded w-2/4 "></h3>
推荐阅读
- c++ - 我想创建一个随机数,将随机数的数字存储到一个数组中,然后将数组存储到一个字符串中
- python - SqlAlchemy 创建表指定模式
- python - 从谷歌地图中抓取城市的经度和纬度
- python - py2App 抛出异常:'unknown mach-o header'
- postgresql - 从异步主要调用的 Rust Postgres(同步)驱动程序导致“无法从运行时内启动运行时”
- c++ - 如何在不破坏现有客户端代码的情况下将类转换为模板类(c++ 17 之前)?
- c# - 为 C# 树提供更好的性能和可读性
- css - 属性 flex-wrap 不能正常工作?
- python - 如何减少 JSON 中的请求时间或将字典键替换为默认键?
- c# - ASP.NET 5 控制器构造函数中过多的依赖注入服务会影响性能和内存吗?