简体   繁体   中英

Why is my JavaScript function "a" not defined?

When I call my JavaScript function B, the JavaScript console in Firefox said that function A is not defined, but on Chrome browser it's defined. And when I call function "A" in body segment:

<input type="button" onclick="A()" value=" ..A.. ">

Firefox said that function B is not defined. Why?

<html>
    <head>
        <script language="javascript" type="text/javascript">
            function B() {
                alert(" hi B ");
                document.write('<br><br><input type="button" onClick="A()" value=" ..A..">');
            };

            function A() {
                alert(" hi A");
                document.write('<br><br><input type="button" onclick="B()" value=" ..b..">');
                if (window.WebCL == undefined) {
                    alert("Unfortunately your system does not support WebCL. ");
                    return false;
                }
            }
        </script>
    </head>
    <body>
        <input type="button" onclick="B()" value=" ..B.. ">
    </body>
</html>

The first write clears the content of the document, resulting in function A being undefined

The problem is that you are calling document.write after the page has loaded, which effectively wipes out the existing content of the page, including the embedded script. You should be using DOM manipulation methods instead.

Try this one:

<html>
<head>
<script language="javascript" type="text/javascript">

var  A = function() {
   alert(" hi A");
   document.write('<br><br><input type="button" onclick="B()" value=" ..b..">');
   if (window.WebCL == undefined) {
     alert("Unfortunately your system does not support WebCL. ");
     return false;
   }
 }  

 function B(){
   alert(" hi B ");     
   document.body.innerHTML = ('<br><br><input type="button" onClick="new A()" value=" ..A..">'); 
 }

    </script>
    </head>

<body>
   <input type="button" onclick="B()" value=" ..B.. ">
</body>

</html>

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