简体   繁体   中英

Javascript function not defined if from a separate file?

Here is my code: I am calling the function run() on the click of a button. run() will call the function main() from the source code of bundle.js. The console logs that the function main() is not defined. I even tried running it in the console itself with no success.


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

<script type="text/javascript">
  function run() {
    main(document.getElementById('playlistUrl').value)
  }
</script>


<input id="playlistUrl" placeholder="Enter a link...">
<button onclick="run()" id="go">Go!</button>

the function run() is defined, but not any funtion from bundle.js

This is working fine,. check your file location or fails in bundle.js file

 //bundle.js file function main(value){ console.log(value); }

 //main.js file function run() { main(document.getElementById('playlistUrl').value) }
 <input id="playlistUrl" placeholder="Enter a link..."> <button onclick="run()" id="go">Go.</button> <script type="text/javascript" src="bundle.js"></script>

Code for index.html:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <script type="text/javascript" src="bundle.js"></script>
</head>
<body>
  

<script type="text/javascript">
  function run() {
    main(document.getElementById('playlistUrl').value)
  }
</script>


<input id="playlistUrl" placeholder="Enter a link...">
<button onclick="run()" id="go">Go!</button>
</body>
</html>

Code for bundle.js:

function main(){
    document.write("Main ran")
}

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