dynamically generated select / options empty in IE but OK in other browsers

穿精又带淫゛_ 提交于 2019-12-10 19:13:20

问题


I'm generating a 'select' element then populating it with options and inserting it into the DOM of my page. Everything's fine in FF, Chrome, Chromium etc. but in IE no options show in the drop-down list but highlights show under the cursor and when I click in the blank list the event handler gets triggered and processes correctly. Here's the relevant HTML area:

<span id="spn_fyear" style="position:absolute; top:7px; left:200px; height:24px; cursor:pointer; color:#000000;" onclick="spn_fyear_onclick(this)">
   <span id="spn_fyearno" style="position:absolute; top:0px; font:italic bold 17px sans-serif; color:#FFFEF2;"><?=$thisPage->getVar('start_year')?></span>
</span>

and here's the javascript in question:

function spn_fyear_onclick(_obj)
{
    //make start year list
    var lstto = document.getElementById('lst_year');
    var topts = new Array();
    var nopt = null;
    for(i=0; i<lstto.options.length; i++)
    {
        topts[i] = lstto.options[i].text;
    }
    var lstf = document.createElement('SELECT');
    lstf.id = "lst_fyear";
    lstf.style.position = "absolute";
    lstf.style.top = "-3px";
    lstf.style.left = "1px";
    lstf.style.fontFamily = "sans-serif";
    lstf.style.fontWeight = "normal";
    lstf.style.fontSize = "12px ";
    lstf.style.width = "55px";
    lstf.style.color = "#000000";
    lstf.style.display = "inline";
    lstf.onchange = lst_fyear_onchange;
    for(i = 0; i < topts.length; i++)
    {
        if(topts[i] != 'undefined')
        {
        nopt = document.createElement('OPTION');
        nopt.text = topts[i];
        nopt.value = topts[i];
        lstf.appendChild(nopt);
        }
    }
    document.getElementById('spn_fyear').appendChild(lstf);
}

In this line: var lstto = document.getElementById('lst_year') I'm creating a reference to an existing select object from which I copy the option data. lst_year gets populated by a php database query when the page first loads. I created the array (var topts = new Array()) in desperation in case IE has a quirk which copies attributes and properties but to no avail. Like I said - everything works like a dream in FF or Chrome both in Linux and Windoze but falls in a heap with IE. I've scoured MSDN etc. for some obscure behaviour but I'm stumped. Any suggestions would be greatly appreciated :) Kind regards, Jen


回答1:


Most likely, your problem is here:

    nopt = document.createElement('OPTION');

Try this method mentioned here:

JavaScript: add extra attribute after new Option()

(I've had a lot of problem with <option> elements and IE before until I started using the new Option constructor.



来源:https://stackoverflow.com/questions/14591707/dynamically-generated-select-options-empty-in-ie-but-ok-in-other-browsers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!