javascript - MS Edge 中的 :scope 伪选择器
问题描述
每当我querySelectorAll
在 Microsoft Edge 中使用:scope
伪选择器时,控制台中都会出现此错误
SCRIPT5022:SCRIPT5022:语法错误
我想知道是否有替代方法querySelectorAll
,我在其中使用此参数::scope > * > table
. 我不想为此使用 jQuery。谢谢。
编辑:
我还想添加它querySelector
本身的作品
好的,这是代码示例:
function pJSON(panel) {
var json = {tables: [], images: [], text: ""};
var tables = Array.from(panel.querySelectorAll(":scope > * > table"));
var images = Array.from(panel.querySelectorAll(":scope > * > img"));
var text = panel.querySelector(":scope > textarea");
tables.forEach(table => {
json["tables"].push(tJSON(table));
});
images.forEach(image => {
json["images"].push(image.outerHTML);
});
if (text) {
json["text"] = text.value;
}
return json;
}
我会再次指出,它适用于除 IE 和 Microsoft Edge 之外的所有浏览器
哦,还有一些可能动态添加的 HTML 示例,这是我调用此方法时的代码:
<div>
<input type="file" multiple=""><br>
<button>Add Table</button><br>
<div>
<table style="display: inline-table;">
<tbody>
<tr>
<td>
<input type="file" multiple=""><br>
<button>Add Table</button><br>
<textarea placeholder="Write some text"></textarea>
</td>
<td>
<input type="file" multiple=""><br>
<button>Add Table</button><br>
<textarea placeholder="Write some text"></textarea>
</td>
<td>
<button style="margin-left: 100px;">x</button>
</td>
</tr>
<tr>
<td>
<input type="file" multiple=""><br>
<button>Add Table</button><br>
<textarea placeholder="Write some text"></textarea>
</td>
<td>
<input type="file" multiple=""><br>
<button>Add Table</button><br>
<textarea placeholder="Write some text"></textarea>
</td>
<td>
<button style="margin-left: 100px;">x</button>
</td>
</tr>
</tbody>
</table>
<button style="margin-left: 100px;">x</button>
</div>
</div>
解决方案
因此,您所追求的实际上是:scope
.
https://github.com/jonathantneal/element-qsa-scope上提供了一个
它的工作原理基本上是首先在要匹配的元素上定义一个足够独特的选择器,并将其添加到传递给 querySelector 的选择器之前。
const li = document.getElementById('target');
console.log('no :scope', li.querySelector('li>a')) // Link
// workaround
const UUID = Date.now()+'';
li.setAttribute('data-scope-uuid', UUID);
console.log('workedaround', li.querySelector('[data-scope-uuid="'+UUID+'"] li>a'));
li.removeAttribute('data-scope-UUID');
// where supported
console.log(':scope', li.querySelector(':scope li>a'));
<ul>
<li id="target"><a>Link</a>
<ul>
<li><a>Sublink</a></li>
</ul>
</li>
</ul>
为了测试本机支持,您可以简单地将 a 包装document.querySelector(':scope') === document.documentElement
在 try catch 块中。
推荐阅读
- python - 如何在python的单个for循环中使用2个索引变量
- azure-devops - 在 VSTS 扩展中打包共享代码
- azure - 如何使用授权进行租户配置 Azure Apimanagement
- node.js - 有没有办法为 mongodb 操作函数创建一个单独的文件并在索引文件中使用这些函数?
- c# - 按条件过滤列表作为元素内的嵌套元素
- python - 是否可以在 Pandas 的 groupby 操作中应用`first()`和`last()`来分隔列?
- mysql - Gem :: 从 MySQL 迁移到 MongoDB 时出现加载错误
- angular - Angular 表单控件基于单选按钮选择进行验证
- python - Pymunk Body 移动而不移动 pymunk 形状顶点
- javascript - 在浏览器上,如何绘制每个 64-128 点的 100k 系列?