Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

call external .js file in html

I have an array.js file and an index.html.

My array.js file looks like this:

function go(){
    var array = new Array();
    array[0] = "Red";
    array[1] = "Blue";
    array[3] = "Green";
    for (var i=0; i < array.length; i++){
        document.write("<li>" + array[i] + "<br />");
    }
}

My index.html file looks like this:

<html>
    <head>
        <script type="text/javascript" src="array.js"></script>
    </head>
    <body>
        <input type="button" onclick="go()" value="Display JS Array"/>
        <script>
            go();
        </script>
    </body>
</html>

When I click the Display JS Array button on the HTML page, nothing happens. I want the array elements to be displayed after I click the button. It should look like:

  • Red
  • Blue
  • Green
like image 562
zmny Avatar asked Aug 07 '12 06:08

zmny


1 Answers

You can change the function by taking the parent element of li elements as parameter.

function go(element){
    var array = new Array();
    array[0] = "Red";
    array[1] = "Blue";
    array[3] = "Green";

    var ul = document.createElement("ul");
    for (var i=0; i < array.length; i++) {
       var li = document.createElement("li");
       li.innerHtml = array[i];
       ul.appendChild(li);
    }
    body.insertAfter(ul, element); 
}


<input type="button" onclick="go(this)" value="Display JS Array"/>
like image 104
sedran Avatar answered Nov 15 '22 17:11

sedran