为什么我的js无法链接到HTML?

时间:2016-01-25 21:28:18

标签: javascript html



<!doctype html>
<html>
	<head>
		<script type="text/javascript">
			var instock=true;
			var shipping=false; 
			
			var elstock= document.getElmentById('stock');
			elstock.className=instock;

			var elship= document.getElmentById('note');
			elship.className=shipping;
			//the text should be updated by values stored
			//in these variables.
		</script>
	</head>
	<body>
			<h1>Elderflower</h1>
			<div id="content">
				<div class="message">Available:
					<span id="stock"></span>
				</div>
				<div class="message">Shipping:
					<span id="shipping"></span>	
				</div>
			</div>
	</body>
</html>
&#13;
&#13;
&#13;

为什么js无法链接到html ???以及我如何将CSS图像链接到js? 例如,如果为true,则显示圆形图像。如果为false,则显示交叉图像。

1 个答案:

答案 0 :(得分:1)

根据Chrome控制台:

  

未捕获的TypeError:document.getElmentById不是函数

您错过了'e',请尝试document.getElementById

此外,一旦修复,您将看到:

  

无法设置属性'className'为null

那是因为你需要在加载页面后运行代码(如评论中所述)。

然后你会遇到另一个问题,因为你正在尝试访问ID为note且没有人的元素,我猜你试图在那里获得shipping

试试这段代码:

<!doctype html>
<html>
	<head>
		<script type="text/javascript">
			function onloaded () {
				var instock=true;
				var shipping=false; 
				var elstock= document.getElementById('stock');
				elstock.className=instock;

				var elship= document.getElementById('shipping');
				elship.className=shipping;
				//the text should be updated by values stored
				//in these variables.
			}
		</script>
	</head>
	<body onload="onloaded()">
			<h1>Elderflower</h1>
			<div id="content">
				<div class="message">Available:
					<span id="stock"></span>
				</div>
				<div class="message">Shipping:
					<span id="shipping"></span>	
				</div>
			</div>
	</body>
</html>