2013-10-08 33 views
0

我正在使用如下所示的嵌入式js脚本制作select元素。我确实看到在页面上有一个select元素,但下拉列表是空白的。默认选择也不显示。我认为CSS不能正常工作的原因是尺寸太小。我做了一个静态选择不是从JS,它是更大。有什么建议么?由JavaScript创建的元素未被CSS文件格式化

* UDPATE *

我追加选择元素,但现在我有两个。一个有选择并且不受CSS影响的,一个是由CSS表单正确格式化的空白。是什么赋予了?

<script> 
      function processCSV(file,parentNode) 
      { 
       var frag = document.createDocumentFragment() 
       , lines = file.split('\n'), option;     
       var intial_option = document.createElement("option"); 

       intial_option.setAttribute("value",""); 
       intial_option.setAttribute("disabled","disabled"); 
       intial_option.setAttribute("selected","selected"); 
       intial_option.innerHTML = "Please select a Plant"; 
       frag.appendChild(intial_option) 

       for (var i = 0, len = lines.length; i < len; i++){ 
        option = document.createElement("option"); 
        option.setAttribute("value", lines[i]); 
        option.innerHTML = lines[i];       
        frag.appendChild(option); 
        } 

       parentNode.appendChild(frag); 
              menuholder.appendChild(parentNode); 
      } 

      var plant_select = document.createElement("select"); 
      var datafile = ''; 
      var xmlhttp = new XMLHttpRequest(); 

      plant_select.setAttribute("class", "selectbox"); 
      plant_select.setAttribute("id", "plant_select"); 



      xmlhttp.open("GET","http://localhost:8080/res/plants.csv",true); 
      xmlhttp.send(); 
      xmlhttp.onreadystatechange = function() 
      { 
       if(xmlhttp.status==200 && xmlhttp.readyState==4) 
       { 
        processCSV(xmlhttp.responseText, plant_select); 
       } 
      } 
     </script> 

的coresponding CSS文件部分如下所示

body 
{ 
    padding: 0; 
    margin: 0; 
background-color:#d0e4fe; 
font-size: 2em; 
     font-family: monospace; 
     font-weight: bold; 
    } 

.menu_container 
{ 
    position: relative; 
    margin: 0 auto; 
} 
.menu_element 
{ 
float: right; 
width: 33%; 
} 
+0

你可以发布生成的HTML吗? –

+2

也许是一个愚蠢的问题 - 但你是否试图通过萤火虫/铬检查生成的代码位,以检查是否正在应用所需的类等? –

+0

哪些浏览器遇到过这个问题? – JAL

回答

2

我相信你需要插入plant_select到DOM。

所以你执行processCSV之前,这取决于你希望你的菜单正是这样做

var body_elem=document.getElementsByTagName('body')[0]; 
body_elem.appendChild(plant_select); 

改变第一线(以追加到哪个元素)。 有关创建和插入文档元素的信息,请参阅https://developer.mozilla.org/en-US/docs/Web/API/Node.appendChild,另请参阅insertBefore

实际上,我没有看到将选项放入文档的位置。

此外,这可能会有所帮助,因为你特别是在IE浏览器 - 而不是 plant_select.setAttribute(“class”,“selectbox”); plant_select.setAttribute(“id”,“plant_select”);

尝试

 plant_select.className="selectbox"; 
    plant_select.id="plant_select"; 

IE尤其是已经有问题与选择不当映射属性的属性。以这种方式设置id和class比setAttribute更可靠。

+0

我将文档片段附加到作为HTML选择对象的parent_select。这应该正确吗?你也意味着插入到DOM中。我创建了它,是否需要附加到div元素才能使用? – TheCodeNovice

+0

你必须把它附加到某个东西上,是的,否则它纯粹存在于JS中,永远不会出现在任何地方。 –

+0

@TheCodeNovice:我在代码中的任何地方都看不到parent_select。我确实看到了创建的plant_select,但没有插入到页面的任何位置(DOM)。您需要插入或追加或者将其前置到页面中的某些内容中,即使它只是“document.body”。 – slebetman