JavaScript 按钮 onclick 不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42530261/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 01:14:00  来源:igfitidea点击:

JavaScript button onclick not working

javascripthtmlfunctionbuttononclick

提问by Martin W

<button onclick="hello()">Hello</button>

<script>
  function hello() {
    alert('Hello');
  }
</script>

This is my code. But it's not working. When I click on the button nothing happens.

这是我的代码。但它不起作用。当我点击按钮时,什么也没有发生。

回答by Michael

Note to other developers coming across this, you can run into this if you use a reserved method names e.g. clear.

请注意遇到此问题的其他开发人员,如果您使用保留的方法名称,例如clear.

<!DOCTYPE html>
<html>
<body>
  <button onclick="clear()">Clear</button>
  <button onclick="clear2()">Clear2</button>
  <script>
  function clear() {
    alert('clear');
  }
  function clear2() {
    alert('clear2');
  }
  </script>
</body>
</html>

回答by Kangjun Heo

How about this?

这个怎么样?

<button id="hellobutton">Hello</button>
<script>
function hello() {
alert('Hello');
}
document.getElementById("hellobutton").addEventListener("click", hello);
</script>

P.S. You should place hello() above of the button.

PS 您应该将 hello() 放在按钮上方。

回答by tk_

I had a similar issue. I had child.jsand a common.jsfiles. In my case, My HTML file was using both the JS files and both of them had a function with the same name,

我有一个类似的问题。我有child.js一个common.js文件。就我而言,我的 HTML 文件同时使用了两个 JS 文件,并且它们都有一个同名的函数,

child.js

孩子.js

function hello(){}

and also

并且

common.js

常见的.js

function hello(){}

After I remove one of these my code works fine and onclick started working. hope this helps!

删除其中之一后,我的代码工作正常,onclick 开始工作。希望这可以帮助!

回答by Edward

Ran into this problem myself so I can confirm something's not right. The difference is that I am generating the DOm Element at runtime. Replacing onclickwith onmousedownseemed to do the trick if you can't find a place to addEventListenerin your code.

我自己遇到了这个问题,所以我可以确认有什么不对。不同之处在于我在运行时生成 DOm 元素。如果您在代码中找不到位置,则替换onclickonmousedown似乎可以解决问题addEventListener

回答by Jishnu V S

There is no problem with your code.. run this snippet

你的代码没有问题..运行这个片段

function hello() {
alert('Hello');
}
<button onclick="hello();">Hello</button>

and if you want to alert this on window load. change your code like this way

如果您想在窗口加载时发出警报。像这样改变你的代码

(function(){
  alert('hello')
})();