标签中的点击功能<script>而不是<button>不起作用



我正在尝试在脚本标记中使用onClick((函数。

<!DOCTYPE html>
<html>
<head>
<script>
const btn = document.getElementById("mainButton");
btn.onclick = function(){
alert("You shouldn't have clicked this button!");
};
</script>
</head>
<body>
<button id="mainButton">Do not click this button</button>
</body>
</html>

当我在互联网上查找语法时,它看起来像上面的内容。

然而,当我运行这个脚本时,它不起作用,我不知道为什么,我尝试的任何其他方法都会变成语法错误。

您需要使用defer或将脚本标记移动到正文的末尾。

<!DOCTYPE html>
<html>
<head>
<script>
document.addEventListener('DOMContentLoaded', () => {
const btn = document.getElementById("mainButton");
btn.onclick = function(){
alert("You shouldn't have clicked this button!");
};
});

</script>
</head>
<body>
<button id="mainButton">Do not click this button</button>

</body>
</html>

<!DOCTYPE html>
<html>
<head>

</head>
<body>
<button id="mainButton">Do not click this button</button>
<script>
const btn = document.getElementById("mainButton");
btn.onclick = function(){
alert("You shouldn't have clicked this button!");
};
</script>
</body>
</html>

最新更新