简体   繁体   中英

function onclick not working .. ... not showing alert box

html code

<input type="button" value="+" onclick="alert()" />

In chrome after inspecting it showing this error Uncaught RangeError: Maximum call stack size exceeded.

javascript

<script type="text/javascript">
  function alert() {
    alert("Hello! I am an alert box!!");
  }
</script>

help me by telling how to solve this

您使用新定义覆盖现有函数定义,新定义另外调用自身,导致太多递归。

那是因为你调用alert()alert()所以它在递归证明。

The alert() is a built-in function, which is not meant to be redefined. Although you redefine, you are calling the same function inside the new function, which is wrong. So, in simple terms, give a different name like myAlert() or something:

function myAlert() {
  alert("Hello! I am an alert box!!");
}

So recursively the alert() function gets called and it overflows the stack.

Solution Snippet

 function myAlert() { alert("Hello! I am an alert box!!"); }
 <input type="button" value="+" onclick="myAlert()" />

You can not have a recursive function such as what you have done here in Javascript as it would continue to loop out of control and consume more memory in the browser. When you call a function from within a function you need to make sure that you are not calling the same function.

As other users mentioned you just need to create your function with a different name than alert() which is an already defined function in javascript, you shouldn't be using that.

I would rather use the standard addEventListener, will make your code cleaner as well as your html

You can do something like this, also you can try it right from this page:

 function myDefinedAlert() { alert("Hello! I am an alert box!!"); } var el = document.getElementById("yourButton"); el.addEventListener("click", myDefinedAlert, false);
 <input id="yourButton" type="button" value="+" />

Press the button, try it, and copy it to your code, let me know if it works :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM