Is it possible to use a for loop in <select> in html? and how?

后端 未结 6 1526
不知归路
不知归路 2021-01-05 20:38

I am trying to use a for loop in html but i dont even know if this is possible. Is it? and if yes how? I dont want to use php. only html and javascript.

this is my

6条回答
  •  心在旅途
    2021-01-05 20:52

    Lots of answers.... here is another approach NOT using document.write OR innerHTML OR jQuery....

    HTML

    
    

    JS

    (function() { // don't leak
        var elm = document.getElementById('foo'), // get the select
            df = document.createDocumentFragment(); // create a document fragment to hold the options while we create them
        for (var i = 1; i <= 42; i++) { // loop, i like 42.
            var option = document.createElement('option'); // create the option element
            option.value = i; // set the value property
            option.appendChild(document.createTextNode("option #" + i)); // set the textContent in a safe way.
            df.appendChild(option); // append the option to the document fragment
        }
        elm.appendChild(df); // append the document fragment to the DOM. this is the better way rather than setting innerHTML a bunch of times (or even once with a long string)
    }());
    

    And here is a Fiddle to demo it.

提交回复
热议问题