这是我的HTML和Javascript,我决定不包括我的CSS,因为不认为它需要。我的代码的目的是创建一个切换开关(如设置应用程序中的iPhone设置),然后使用javascript添加事件监听器。我让Listener应用于button元素。当我单击按钮时,函数start()应该激活,正如您所看到的,切换功能应该在启动onclick事件时激活。按下按钮时应该更改背景颜色。但是,它根本不会改变颜色。它就像切换调用不起作用。我可以单独调用切换功能,但这会在页面加载时更改颜色。单击按钮时它应该可以工作。感谢任何可以帮助我的人。
<!DOCTYPE html>
<html>
<head>
<title>Light Switch</title>
<link rel="stylesheet" href="light.css" />
</head>
<body id="body">
<button id="submit">Submit
<label id="switch">
<input type="checkbox" checked>
<span class="slider"></span>
</label>
</button>
<script src="light.js"></script>
</body>
</html>
//This js file was separate from my HTML file and was linked
function start() {
var submit = document.getElementById("submit");
submit.addEventListener("onclick", toggle);
};
function toggle() {
var color = document.getElementById("body");
color.style.backgroundColor = "black";
};
start();
答案 0 :(得分:1)
将onclick
更改为仅click
。此外,似乎不需要start()
功能。
document.getElementById("submit").addEventListener("click", toggle);
function toggle() {
console.log('c')
document.getElementById("body").style.backgroundColor = "black";
};
<body id="body">
<button id="submit">Submit
<label id="switch">
<input type="checkbox" checked>
<span class="slider"></span>
</label>
</button>
</body>
另外,使用onclick
您不需要addEventListener
var getSubmitButton = document.getElementById("submit");
getSubmitButton.onclick = toggle;
function toggle() {
document.getElementById("body").style.backgroundColor = "black";
};
<body id="body">
<button id="submit">Submit
<label id="switch">
<input type="checkbox" checked>
<span class="slider"></span>
</label>
</button>
</body>