[英]JS function doesn't change box color
JS只是拒绝执行任何操作-不显示console.log,不显示任何错误,不执行任何操作。
JS真的没有任何生命迹象-我尝试制作document.getelementbyid(box1)
和(“ #box”)和(“ box”)是因为互联网上的人们都在使用所有这些,并且它可以工作。
试图使事件嵌入HTML中以调用该函数,并尝试在window.onload等上调用该函数。
尝试更改文本,颜色,大小和边距-没有任何效果。 有时会出现null错误-表示JS由于某种原因无法获取样式值。
var box = document.getElementById("#box1"); function changeColor() { var box = document.getElementById("#box1"); box.style.backgroundColor = 'red'; }
#box1 { height: 100px; width: 100px; background-color: #B9E257; } #box2 { height: 100px; width: 100px; background-color: #69ADE1; }
<!DOCTYPE html> <html> <head> <link rel="stylesheet" href="N.css" type="text/css"> </head> <body> <div id="box1">1</div> <div id="box2">2</div> <button onclick="changeColor()">Go!</button> <script src="N.js" type="text/javascript"></script> </body> </html>
为什么在地球上它不起作用?
Document方法getElementById()返回一个Element对象,该对象表示其id属性与指定字符串匹配的元素。 由于如果指定了元素ID,则它们必须是唯一的,因此它们是快速访问特定元素的有用方法。
有关更多信息,请访问文档
ID是区分大小写的字符串,在文档中是唯一的。
请检查以下运行示例:
function changeColor() { var box = document.getElementById("box1"); console.log(box); box.style.backgroundColor = 'red'; }
#box1 { height: 100px; width: 100px; background-color: #B9E257; } #box2 { height: 100px; width: 100px; background-color: #69ADE1; }
<head> <link rel="stylesheet" href="N.css" type="text/css"> </head> <body> <div id="box1">1</div> <div id="box2">2</div> <button onclick="changeColor()">Go!</button> <script src="N.js" type="text/javascript"></script> </body>
您的JS抛出错误仅仅是因为您在document.getElementById
中使用#
,这是不允许的。 您需要在jQuery中而不是JS中为ID
定义#
。
这是更新的代码。 只是从document.getElementById
删除了#
,我没有做其他任何事情。
function changeColor() { var box = document.getElementById("#box1"); box.style.backgroundColor = 'red'; }
#box1 { height: 100px; width: 100px; background-color: #B9E257; } #box2 { height: 100px; width: 100px; background-color: #69ADE1; }
<head> <link rel="stylesheet" href="N.css" type="text/css"> </head> <body> <div id="box1">1</div> <div id="box2">2</div> <button onclick="changeColor()">Go!</button> <script src="N.js" type="text/javascript"></script> </body>
如果您真的喜欢那个#,那么请使用var box = document.getElementById(“#box1”); 做
var box = document.querySelector("#box1");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.