JS只是拒绝执行任何操作-不显示console.log,不显示任何错误,不执行任何操作。
JS真的没有任何生命迹象-我试着使document.getelementbyid(box1)
和(“ #box”)和(“ box”)成为现实,因为互联网上的人们都在使用所有这些东西并且它起作用了。 / p>
试图使事件嵌入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>
为什么在地球上不起作用?
答案 0 :(得分:2)
Document方法getElementById()返回Element对象 表示其id属性与指定属性匹配的元素 串。由于如果指定,则元素ID必须是唯一的, 它们是快速访问特定元素的有用方法。
有关更多信息,请访问docs
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>
答案 1 :(得分:0)
您的JS抛出错误只是因为您在<div class="Timeline">
<div class="event1">
<div class="event1Bubble tooltip">
<span class="tooltiptext">id: 12345</br>
starts_on: 2019-03-07</br>
start_reason: something</br>
ends_on:</br>
end_reason:</br>
type: something
</span>
<div class="eventTime">
<div class="DayDigit">10</div>
<div class="Day">
Wednesday
<div class="MonthYear">September 2018</div>
</div>
</div>
<div class="active">Active</div>
</div>
</div>
</div>
中使用#
,这是不允许的。您需要在jQuery中而不是在JS中为document.getElementById
定义#
。
这是更新的代码。只是从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;
}
答案 2 :(得分:0)
如果您真的喜欢那个#,那么 var box = document.getElementById(“#box1”); 做
var box = document.querySelector("#box1");