简体   繁体   中英

How do I implement external js file in html webpage?

I created the following JS in an external file:

var n = Math.floor((Math.random() * 1000) + 1); {
   window.alert(n);  
    if (n) 
      var output = "";
      if (n % 3 == 0)
        output += "Rock";
      if (n % 5 == 0)
        output += "star";
      window.alert(output || n); }

I want to implement this code when a person clicks a button on the webpage.

Would I use need to place this into my html page: Click me?

The cleanest way would be to put this code in a function, and then bind the click event of your button to execute that function.

For the function, something like:

function rockstar() {
    ... your code ...
}

The call rockstar() when your button is clicked.

Create an external file Rockstar.js. Add a Funktion:

function rockstar() {
var n = Math.floor((Math.random() * 1000) + 1); 
console.log(n);  
if (n) 
  var output = "";
if (n % 3 == 0)
  output += "Rock";
if (n % 5 == 0)
  output += "star";
console.log(output, n); 
} 

now add it to or section inyour HTML with

<script src=" Rockstar.js "></script>

you can bind rockstar() to an onclick event or call in a script Tag from here.

hope this helps

edit: use console.log instead of alert. alert causes all function to halt.

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