简体   繁体   中英

Javascript function not printing onto the console

Why the following is not being printed to the console? I cant understand what the error is ..can Some one help me debug the error.

<script type="text/javascript" src="static/js/scenes/scene_world.js">
  //document.write("<button type='button' onclick='click();'>Click Me!</button>");
  //document.write("<input id='clickMe' type='button' value='clickme' onclick='lol();' />");
    console.log("lol");
  </script>

inside scene_world.js:

  function lol(){
  console.log("lol");
  }

Tired accessing it from outside like this:

  <script type="text/javascript" src="static/js/scenes/scene_world.js">
  //document.write("<button type='button' onclick='click();'>Click Me!</button>");
  //document.write("<input id='clickMe' type='button' value='clickme' onclick='lol();' />");

  </script>
  <script>
  document.write("<input id='clickMe' type='button' value='clickme' onclick='lol();' />");
  </script>

But it is giving me this error:

Uncaught ReferenceError: lol is not defined

script tags with an src attribute cannot have inline content as well. You need to create a new script block for that.

According to the official html specification:

If the src has a URI value, user agents must ignore the element's contents and retrieve the script via the URI

For details see the Reference

From the w3c .

If the src attribute is not set, user agents must interpret the contents of the element as the script. If the src has a URI value, user agents must ignore the element's contents and retrieve the script via the URI.

You should clear everything between the <script> tags with a src attribute and put your codes in a separate <script> tag.

<script type="text/javascript" src="static/js/scenes/scene_world.js"></script>
<script>
document.write("<input id='clickMe' type='button' value='clickme' onclick='lol();' />");
</script>

See DEMO .

Okay, after your edit, scene_world.js is fine. Why use document.write(..) ?

<script type="text/javascript" src="static/js/scenes/scene_world.js">
</script>
<input id='clickMe' type='button' value='clickme' onclick='lol();'/>

Should work when button is clicked.

For direct call:

<script type="text/javascript" src="static/js/scenes/scene_world.js">
</script> 
<script type="text/javascript">
    lol();
</script>

Have you inserted those script tags inside head or body ?

It was not printing on to the console because the function i tried invoking was inside another function. So it was not properly invoked. A careless mistake.

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