“无法在'Node'上执行'appendChild'”?

时间:2019-05-21 01:12:41

标签: javascript

所以我正在尝试使用JavaScript制作SVG系列,但是它不起作用。 Chrome控制台显示“未捕获的TypeError:无法在'Node'上执行'appendChild':参数1的类型不是'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。出现一条线,但应出现另一条垂直线。我只想知道为什么它不起作用以及如何解决它。谢谢! CodepenJSFiddle

1 个答案:

答案 0 :(得分:1)

玩弄您的代码,看起来线条之间是相互重叠的。看来您为X设置了line2值不正确。如果将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');