<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <link rel="stylesheet" href="css.css"> <script src="3.js"></script> </head> <body> <div id="rct" onclick="click()"></div> <button class="butt" onmousedown="click()">ss</button> </body> <script> window.onload=function (){ alert("1100"); click() { var rct= document.getElementById('rct'); rct.style.backgroundColor="#003366" console.log("a") } } </script> 请问这段代码的onclick为什么不执行
时间: 2023-08-14 19:11:59 浏览: 760
这段代码的onclick没有执行,是因为click()函数的语法有误,应该写成function click() {}的形式。另外,onload事件后的click()函数定义应该放在window.onload函数外面,或者使用匿名函数包装。修改后的代码如下:
```
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="css.css">
<script src="3.js"></script>
</head>
<body>
<div id="rct" onclick="click()"></div>
<button class="butt" onmousedown="click()">ss</button>
</body>
<script>
function click() {
var rct = document.getElementById('rct');
rct.style.backgroundColor = "#003366";
console.log("a");
}
window.onload = function() {
alert("1100");
click();
}
</script>
</html>
```
阅读全文