【发布时间】:2020-07-18 23:12:18
【问题描述】:
所以我正在尝试使用 JavaScript 制作 SVG Line,但我不断收到一个我不理解的错误。 Chrome 控制台说,
未捕获的类型错误:无法在“节点”上执行“appendChild”:参数 1 不是“节点”类型。
下面是我的代码:
function play(x, y) {
var line1 = document.createElementNS('http://www.w3.org/2000/svg', 'line');
line1.setAttribute('x1', x - 25);
line1.setAttribute('x2', x + 25);
line1.setAttribute('y1', y - 25);
line1.setAttribute('y2', y + 25);
line1.setAttribute('stroke', 'white');
line1.setAttribute('stroke-width', '2');
var line2 = document.createElementNS('http://www.w3.org/2000/svg', 'line');
line2.setAttribute('x1', x + 25);
line2.setAttribute('x2', x - 25);
line2.setAttribute('y1', y + 25);
line2.setAttribute('y2', y - 25);
line2.setAttribute('stroke', 'white');
line2.setAttribute('stroke-width', '2');
document.getElementById('game').appendChild(line1);
document.getElementById('game').appendChild(line2);
}
<!DOCTYPE html>
<html>
<head>
<title>Tic-tac-toe</title>
</head>
<body style='background-color: black; margin: 0px;'>
<svg id='game' width='300' height='300' style='margin: auto; position: relative; top: 50px; display: block; background-color: #000; border: 2px solid white;'>
<rect x='0' y='0' width='100' height='100' style='stroke-width: 2; stroke: #fff' onclick='play(50, 50);'/>
<rect x='100' y='0' width='100' height='100' style='stroke-width: 2; stroke: #fff' onclick=''/>
<rect x='200' y='0' width='100' height='100' style='stroke-width: 2; stroke: #fff' onclick=''/>
<rect x='0' y='100' width='100' height='100' style='stroke-width: 2; stroke: #fff' onclick=''/>
<rect x='100' y='100' width='100' height='100' style='stroke-width: 2; stroke: #fff' onclick=''/>
<rect x='200' y='100' width='100' height='100' style='stroke-width: 2; stroke: #fff' onclick=''/>
<rect x='0' y='200' width='100' height='100' style='stroke-width: 2; stroke: #fff' onclick=''/>
<rect x='100' y='200' width='100' height='100' style='stroke-width: 2; stroke: #fff' onclick=''/>
<rect x='200' y='200' width='100' height='100' style='stroke-width: 2; stroke: #fff' onclick=''/>
</svg>
</body>
</html>
当您单击左上角的框时,应该会出现一个 X。出现一条线,但应该出现另一条垂直线。我只想知道为什么它不起作用,如何修复它,以及错误意味着什么。谢谢!
【问题讨论】:
-
你说在 chrome 上什么都没有出现,但是你在 chrome 上运行的例子似乎复制了 sn-p 中发生的事情
-
我不明白你的问题:你认为调试器会给出花哨的错误信息吗?
-
@Snel23 是的,我刚看到这个,我一定是忘记保存我的代码了。但是,应该会出现另一条垂直线
-
@MisterJojo 是的,这就是 Chrome 调试器。它只是说了一些只有少数人能理解的奇怪事情。我要问的是为什么没有出现另一条垂直线?
标签: javascript