简体   繁体   中英

Calling a function i javascript from HTML

New to js/html so help is needed.

i have this simple html file:

   <html>

   <script type="text/javascript" src="rps.js">

   var numOfRounds = 25;
   var result = startGame(numOfRounds,player1,player2 );
   document.write(result.p1+":"+result.p2);

   </script>

   </html>

and as you can see the function im calling to is startGame(...)

this is the function:

   function startGame(rounds, player1, player2) {

       var counter = 0;
       while (counter < rounds) {
       player1.itemChosen = player1.play();
       player2.itemChosen = player2.play();

      player1.feedback(player2.itemChosen);
      player2.feedback(player1.itemChosen);

      counter++;
   }
   return  {p1: player1.getW(),p2: player2.getW() }

  };

but for some reason when i try to debug it (chrome) the startGame function is not called at all.

any ideas?

You cannot have any code inside a script tag with a src attribute.

Either use a script tag with a src attribute, or a script tag without src attribute and with code inside it, or both.

   <script type="text/javascript" src="rps.js"></script>

   <script type="text/javascript">
   var numOfRounds = 25;
   var result = startGame(numOfRounds,player1,player2 );
   document.write(result.p1+":"+result.p2);

   </script>

You cannot have any code inside a script tag with a src attribute.

if you want to use any other variable or component of attribute than you either use a script tag with a src attribute, or a script tag without src attribute and with code inside it, or both.

<script type="text/javascript" src="rps.js">        </script>

than use another script like

<script type="text/javascript">
 var numOfRounds = 25;


 var result = startGame(numOfRounds,player1,player2 );



document.write(result.p1+":"+result.p2);



</script>

like this....

Try putting your inline js in another script tag

<script type="text/javascript" src="rps.js"></script>
<script type="text/javascript">

   var numOfRounds = 25;
   var result = startGame(numOfRounds,player1,player2 );
   document.write(result.p1+":"+result.p2);

</script>

I'm guessing startGame is declared in rps.js.

You don't have a script tag for the function try to add as

<script type="text/javascript">
//Your function code
</script>

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