confirm function is not working

自作多情 提交于 2019-12-10 15:54:07

问题


*<html>
<head>
<title>practise</title>
<script type="text/javascript">
function confirm() {
    var r = confirm("Press the button");
    if (r == true) {
        alert("You are right");
    } else {
        alert("You are wrong");
    }
}

</script>
</head>

<body>
        <input type="button" name="submit" value="showtime" onclick="confirm()"/>
    </div>
</body>
</html>*

I want to know what's the problem. It is not working but it is the same as in http://www.w3schools.com/js/js_popup.asp


回答1:


  1. You are recursively calling confirm() and it's in an infinite loop
  2. You have a * at the beginning and end of the document
  3. As kennebec pointed out, you're overwriting window.confirm
  4. You have a hanging end </div> in the <body>

http://jsfiddle.net/cvyyL/

<html>
   <head>
      <title>practise</title>
      <script type="text/javascript">
         function show_confirm() {
            var r = confirm("Press the button");
            if (r == true) {
               alert("You are right");
            } else {
               alert("You are wrong");
            }
         }    
      </script>
   </head>
   <body>
      <input type="button" name="submit" value="showtime" onclick="show_confirm()"/>
   </body>
</html>



回答2:


First off, you overwrote window.confirm... Then you call the new confirm, forever, or until there is too much recursion...




回答3:


Your function has the same name as the built-in window.confirm() function, so your function is replacing that one. Then within your function you call confirm() which means it is recursively calling itself.

It should work if you simply rename your function to something else. (E.g., the w3schools page you link to calls its function 'show_confirm'.)




回答4:


You need to return the value from the confirm() function, and return that value in the onclick handler if you're trying to use it to prevent the submission.

IMO it's a really bad idea to name your function "confirm", though, since there's already a method called that, and you may recurse until the browser melts.

Also, saying something "doesn't work", without saying what it does and what you expect it to do, makes answering questions difficult.




回答5:


confirm() is a predefined function in javascript so you can't use it for the name of one of your functions. It is an error, rename the function and it will work properly.

Also remove the * from the start and the end.



来源:https://stackoverflow.com/questions/7844558/confirm-function-is-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!