JavaScript button onclick not working

2020-03-08 08:56发布

<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.

5条回答
甜甜的少女心
2楼-- · 2020-03-08 08:57

I had a similar issue. I had child.js and a common.js files. 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

function hello(){}

and also

common.js

function hello(){}

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

查看更多
我想做一个坏孩纸
3楼-- · 2020-03-08 09:08

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.

查看更多
啃猪蹄的小仙女
4楼-- · 2020-03-08 09:10

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 onclick with onmousedown seemed to do the trick if you can't find a place to addEventListener in your code.

查看更多
放荡不羁爱自由
5楼-- · 2020-03-08 09:16

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')
})();

查看更多
▲ chillily
6楼-- · 2020-03-08 09:24

Note to other developers coming across this, you can run into this if you use a reserved method names e.g. 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>

查看更多
登录 后发表回答