简体   繁体   中英

calling an external .js file from html file

my main.js looks like this

function myfunction(){
  alert("Button Pressed");
}

The HTML file

<head>
<title>meteorTest</title>
<script type="javascript" src="main.js">
</script>
<!--<script>
    function myfunction(){
        alert("hello");
    }
</script>-->
</head>

<body>
<h1>Welcome to Meteor!</h1>
<input type="button" onclick="myfunction();" value="Click me!" />
</body>

If i run from the internal myfunction() it works fine. When I comment that out and run from the external .js I get this error:

"(index):1 Uncaught ReferenceError: myfunction is not defined at HTMLInputElement.onclick ( http://localhost:3000/:1:1 )"

Both the HTML and the .js are located in the same directory, so the path in src="main.js" should be right.

在外部脚本上,您当前具有type="javascript"但需要type="text/javascript"才能对其进行评估。

Ok.. Analyzing your problem; give a try to button tag and JQuery click event.

  1. Calling from button tag

meteorTest

 <body> <h1>Welcome to Meteor!</h1> <button onclick="myfunction()" value="Click me!" ></button> </body> 
  1. jQuery Click Event (Note:- Do include jquery.js/ jquery.min.js file)
     <title>meteorTest</title> <script type="text/javascript" src="main.js"> </script> </head> <body> <h1>Welcome to Meteor!</h1> <button id="callme" value="Click me!" ></button> </body> 

In Javascript side (main.js)

$("#callme").click(function(){
  myfunction();
});

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