You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Firefox68.0.1/Chrome75.0中按钮点击事件无法执行问题求助

解决按钮点击无响应的问题

我来帮你排查下这个问题,你的代码里有几个关键错误导致点击按钮没反应,咱们一步步来修正:

  • script标签属性写错了:HTML里的script标签应该是type="text/javascript",你写成了script="text/javascript",这会让浏览器无法正确加载JS文件。
  • window.onload赋值方式错误:JS里window.onload = applyBehaviour();这行加了括号,会直接立即执行applyBehaviour函数,而不是等页面加载完成后再触发。正确写法是把函数引用赋值给onload,也就是去掉括号:window.onload = applyBehaviour;
  • 事件绑定选错了对象和写法:按钮元素没有onsubmit事件,这个事件属于form表单;而且你绑定事件时加了括号behave(),会直接执行函数而不是点击时触发。应该给按钮绑定onclick事件,并且只赋值函数引用:oButton.onclick = behave;

修正后的HTML文件(jsb-06.html)

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8">
<title> Event Handler through a Button</title>
<script type="text/javascript" src="jsb-06.js"></script>
</head>
<body>
<form action="">
<div>
<button id="action">Click Me</button>
</div>
</form>
</body>
</html>

修正后的JS文件(jsb-06.js)

// tell the JS to run this script when the browser has finished loading the page
window.onload = applyBehaviour;
// define a function and apply its behaviour
function applyBehaviour() {
// ensure a DOM aware user agent
if (document.getElementById) {
var oButton = document.getElementById("action");
// if it exists apply behaviour
if (oButton) {
oButton.onclick = behave;
}
}
}
// what to do when the button is clicked
function behave() {
alert("Click is Completed !!");
}

修改完成后,在Firefox(ver.68.0.1)和Chrome(ver.75.0)里点击"Click Me"按钮,就能正常弹出预期的提示框了。

内容的提问来源于stack exchange,提问作者Divyendu Deo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 06:23:43