由 JavaScript 创建的元素未被 CSS 文件格式化

Element created by JavaScript not being formated by CSS file

本文关键字:CSS 文件 格式化 元素 JavaScript 创建      更新时间:2023-09-26

我正在使用嵌入式js脚本制作一个选择元素,如下所示。我确实看到页面上有一个选择元素,但下拉列表是空白的。默认选择也不会显示。我认为CSS不起作用的原因是大小太差了。我做了一个静态选择,而不是从js,它要大得多。有什么建议吗?

*

乌德帕特*

附加了选择元素,但现在我有两个。一个具有选择且不受 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>

对应的 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%;
}
我相信

您需要将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 和类比 setAttribute 更可靠。