所以我尝试使用 JavaScript 制作 SVG 线,但我不断收到我不明白的错误。 Chrome 控制台显示,
Uncaught TypeError: Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'.
下面是我的代码:
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。出现一条线,但应该出现另一条垂直线。我只是想知道为什么它不起作用,如何修复它,以及错误的含义。谢谢!
最佳答案
玩弄你的代码,看起来线条是在彼此之上绘制的。您似乎为 line2
设置了错误的 X
值。如果将 line2
的代码更改为以下内容,它将起作用。
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');
关于javascript - "Failed to execute 'appendChild' on 'Node'”是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56229887/