简体   繁体   中英

Why won't my JavaScript load on my webpage (using window.onload)?

I'm trying to develop an HTML Page within Adobe Dreamweaver using the Live Preview function (where I view the webpage on a local server) and my JavaScript is being finicky. Im trying to populate a dropdown menu with a JS array and my previous testing worked, but now when I try to get the script to run automatically, either a) nothing happens or b) the button flashes suggesting it was updated but still shows blank. Any help would be appreciated!

    <script>
    function start() {

        var arrOptions = []; //arrOptionsCollection with HTML tags
        var arrOptionsCollection = [0, 1, 2]; //Values for dropdown

        arrOptions.push("<option value='Select From List...'>Select From List...</option>") //Dropdown Default


        //Adds HTML tags to arrOptionsCollections
        for (var i=0, n = arrOptionsCollection.length; i < n; i++) { =
            arrOptions.push("<option value='" + arrOptionsCollection[i] + "'>" + arrOptionsCollection[i] + "</option>");
        }

        //Transfers arrOptions to actual HTML
        document.getElementById("district-select").innerHTML = arrOptions.join();
    }

    document.getElementById("form-select").onload = function() {start()};

</script>

<body onload="start();">
<form id="form-select">
    <select id="district-select">
        <!--Script Inserts Options Here-->
    </select>

</form>

I wonder what's the role of the = at the beginning of your for loop. Simply, it doesn't make any sense.

So instead of:

for (var i=0, n = arrOptionsCollection.length; i < n; i++) { =

Put:

for (var i=0, n = arrOptionsCollection.length; i < n; i++) {

Here is your code:

 function start() { var arrOptions = []; //arrOptionsCollection with HTML tags var arrOptionsCollection = [0, 1, 2]; //Values for dropdown arrOptions.push("<option value='Select From List...'>Select From List...</option>") //Dropdown Default //Adds HTML tags to arrOptionsCollections for (var i=0, n = arrOptionsCollection.length; i < n; i++) { arrOptions.push("<option value='" + arrOptionsCollection[i] + "'>" + arrOptionsCollection[i] + "</option>"); } //Transfers arrOptions to actual HTML document.getElementById("district-select").innerHTML = arrOptions.join(); } document.getElementById("form-select").onload = function() {start()};
 <body onload="start();"> <form id="form-select"> <select id="district-select"> <!--Script Inserts Options Here--> </select> </form>

Here is a living demo: https://codepen.io/marchmello/pen/yLYbYjw?editors=1010

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