我正在将一些 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/