gpt4 book ai didi

javascript - 使用 document.evaluate() 提取 元素?

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:33:23 29 4
gpt4 key购买 nike

我正在尝试使用 document.evaluate()<svg> 中提取某些子元素元素。但是我通过提取 <svg> 遇到了问题本身。我可以提取所有内容直到 <svg> ,但没有进一步。例如,这很有效:

document.evaluate('//*[@id="chart"]/div/div[1]/div', document, null, XPathResult.ANY_UNORDERED_NODE_TYPE, null).singleNodeValue)

这给了我(缩短):

<div style="position: absolute; left: 0px; top: 0px; width: 100%; height: 100%;" aria-label="Et diagram.">
<svg width="600" height="400" aria-label="Et diagram." style="overflow: hidden;"></svg>
<div aria-label="En repræsentation i tabelformat af dataene i diagrammet." style="position: absolute; left: -10000px; top: auto; width: 1px; height: 1px; overflow: hidden;"></div>
</div>

然后我会假设简单的

//*[@id="chart"]/div/div[1]/div/svg

会给我 <svg> - 但没有任何作用。尝试了所有响应类型:

for (var type=XPathResult.ANY_TYPE; type<XPathResult.FIRST_ORDERED_NODE_TYPE+1; type ++) {
console.dir(
document.evaluate('//*[@id="chart"]/div/div[1]/div/svg', document, null, type, null)
);
}

我得到 invalidIteratorState , 无效 singleNodeValuesnapshotLength共 0 个。

演示 -> http://jsfiddle.net/hw79zp7j/

evaluate()有没有限制我没听说过,还是我做的完全错了?

为了澄清,我的最终目标是能够提取例如谷歌可视化 xAxis <text>单行代码中的元素。就像现在一样(见演示)我必须遍历 <svg>通过使用多个 querySelectorAll/getElementsByTagName等,这不是很可读,维护友好或优雅。捕获xpath就好了来自谷歌开发者工具并在一行中重用它。

最佳答案

SVG 元素位于命名空间 http://www.w3.org/2000/svg 中,要使用 XPath 选择命名空间中的元素,您需要将前缀绑定(bind)到命名空间 URI 并使用路径中的那个前缀来限定元素名称,例如svg:svg。因此,使用解析器作为 evaluate 的第三个参数,它将您可以选择的前缀(例如 svg)映射到上面提到的命名空间 URI。

document.evaluate('//*[@id="chart"]/div/div[1]/div/svg:svg', document, 
function(prefix) {
if (prefix === 'svg')
{
return 'http://www.w3.org/2000/svg';
}
else
{
return null;
}
}, type, null)

关于javascript - 使用 document.evaluate() 提取 <svg> 元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31162358/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com