我正在尝试编写一个脚本,它将动态创建一个SVG元素并显示它。但是,当我设置SVG元素的ID,然后尝试使用Document.getElementById()访问它时,它返回null。我使用window.onload来确保在调用脚本之前已经加载了文档。
<body>
<script>
function buildSVG(color) {
const shape = `<rect x="0" y="0" width="90" height="90" stroke="black" fill="${color}"/>`;
return shape;
}
function addSVG(color) {
let svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
svg.id = "svgID";
let elem = document.getElementById("svgID");
elem.setAttribute('width', '600');
svg.setAttribute('height', '250');
svg.innerHTML = buildSVG(color);
svg.setAttribute('style', 'border: 1px solid black');
document.body.appendChild(svg);
}
window.onload = addSVG("cyan");
</script>
</body>
我希望显示一个青色的正方形。但是,我收到错误消息"cannot read property setAttribute of null“。
我能做些什么来解决这个问题呢?
发布于 2019-05-31 06:49:54
在创建svg-element时,在分配的变量中已经有了对它的引用。不需要再次从文档中获取它。这甚至是不可能的,因为它还没有添加到文档中。以下是更正后的代码:
function buildSVG(color) {
const shape = `<rect x="0" y="0" width="90" height="90" stroke="black" fill="${color}"/>`;
return shape;
}
function addSVG(color) {
let svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
svg.id = "svgID";
svg.setAttribute('width', '600');
svg.setAttribute('height', '250');
svg.innerHTML = buildSVG(color);
svg.setAttribute('style', 'border: 1px solid black');
document.body.appendChild(svg);
}
window.onload = addSVG("cyan");
// after 1 second: get the svgID-element and change the border.
setTimeout(function(){
document.getElementById('svgID').setAttribute('style', 'border: 1px dashed red');
}, 1000);
https://stackoverflow.com/questions/56386573
复制相似问题