gpt4 book ai didi

javascript - setAttributeNS 不允许为空

转载 作者:搜寻专家 更新时间:2023-10-30 21:10:27 26 4
gpt4 key购买 nike

我正在将一些 JavaScript 转换为 Typescript。

在下面的代码中,null 被拒绝,因为它不能被分配给一个字符串参数。

var svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');

svg.setAttributeNS(null, 'width', canvas.width.toString());
svg.setAttributeNS(null, 'height', canvas.height.toString());

检查 svg 的类型,我们发现它是 SVGSVGElement(是的,SVG 在名称中出现了两次)。我尝试显式指定类型 svg: SVGElement 并能够将创建的元素分配给它,但对 null 问题没有影响。

Difference between setAttribute and setAttributeNS(null, 的公认答案说当属性没有定义的命名空间时,我必须传递空值。然后它建议我使用 setAttributeNS“以保持一致性”。

但我不能传递 null。我应该传递一个空字符串吗?那行得通吗?还是应该使用 DOM 级别 1 setAttribute 方法?

最佳答案

如果文档说 null 是允许的,那么不幸的是,这似乎是对定义的疏忽。

幸运的是,您可以轻松解决这个问题。 Typescript 支持接口(interface)声明合并,因此您可以在文件中重新声明 Element 接口(interface)并添加缺少的方法:

var svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
interface Element {
setAttributeNS(namespaceURI: null, qualifiedName: string, value: string): void;
}
declare var canvas : HTMLCanvasElement;

svg.setAttributeNS(null, 'width', canvas.width.toString());
svg.setAttributeNS(null, 'height', canvas.height.toString());

关于javascript - setAttributeNS 不允许为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46066556/

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