<input></input> in innerHTML 中不起作用


<input></input> in innerHTML not working

>我用javascript创建了一个下拉列表,我填充它从MySQL数据库中获取数据。

遇到的问题是我无法将下拉列表放在内部HTML代码中。

这是我使用 JS 创建下拉列表所写的内容:

var mySpan = document.getElementById('myDiv');
var myLine = document.getElementById('testcat');
myLine.value++;
// Create select
var selection = document.createElement('select');
selection.setAttribute('name',"category[]");
mySpan.appendChild(selection); 
// Create Option
createSelectOption(selection);
// Create the container
var ni = document.getElementById('myDiv');
ni.setAttribute('style', 'width:790px;');
...........
...........

然后我创建其他东西并创建HTML代码,我使用:

newdiv.innerHTML = '<div class="table">.........</div>';
ni.appendChild(newdiv);

这是 HTML 的一部分:

// test dropdown list
<input name="testcat" id="testcat" type="hidden" value="0" />   
<div id="myDiv"></div>

正如您在上面的代码中看到的那样,我测试了我的下拉列表,如果我在 HTML 中声明<input name="testcat" id="testcat" type="hidden" value="0" />(我的意思是在 <body></body> 中),它可以工作,但是如果我在 innerHTML 中使用相同的代码,FireBug 告诉我:"myLine 为空;myLine.value++;".

有什么帮助吗?

您不能使用 innerHTML 作为文本为元素分配 ID - 该 ID 不会在 DOM 上注册。您需要首先创建元素,为其分配 ID,然后将该元素放入 DOM 中。

你可能会发现使用jQuery更容易:

var input = document.createElement("input"); 
input.id="testcat"; 
input.innerHTML = "testcat" ;
$('somediv').appendChild(input); 
这是我

在旧代码中所做的:

var selectcat = document.createElement("select");
selectcat.name = "category[]";
selectcat.options[0] = new Option("","");
selectcat.options[1] = new Option("cat1","cat1");
selectcat.options[2] = new Option("cat2","cat2");
..........
..........
selectcat.options[12] = new Option("cat1","cat12");

和使用的:

newdiv.innerHTML = '<div class="table"><ul><li><select name="category[]"><option value=""></option><option value="cat1">cat1</option><option value="cat2">cat2</option></select></li></ul></div>';

但是现在我必须从MySQL数据库中获取值。

所以我创建了这个函数:

function createSelectOption(element)
    {
        var objSelect = ele;
        var Item = new Option("", "");
        objSelect.options[objSelect.length] = Item;
        <?
        while($categ = mysql_fetch_array($resultf_categ))
        {
        ?>
            var Item = new Option("<?=$categ["cat_name"];?>", "<?=$categ["cat_name"];?>");
            objSelect.options[objSelect.length] = Item;
        <?
        }
        ?>
    }

但是仍然不明白如何直接在我的 innerHTML 中使用。很抱歉愚蠢的问题,但我真的被困在这里了。