尽管我应该有一个组合框,但我得到的是一个空白页。数组填充得很好 - 我警告了一些值并且它有效,但组合框没有显示任何内容。 我想做的是根据从数组检索的数据创建一个组合框,但它似乎不起作用。
<script type="text/javascript">
var array = {"ADDRESS_ID":["3","5"],"ADDRESS_PLACE":["a","b"],"ADDRESS_PARENT":[null,null],"TYPE":["0","1"]};
var i, theContainer, theSelect, theOptions, numOptions, anOption;
theContainer = document.createElement('div');
theContainer.id = array['TYPE'][0];
theSelect = document.createElement('select');
theSelect.name = 'name_of_select';
theSelect.id = 'id_of_select';
theSelect.onchange = function () {
alert('You selected option '+this.selectedIndex);
};
// Add some <option>s
numOptions = array.length;
for (i = 0; i < numOptions; i++) {
anOption = document.createElement('option');
anOption.value = array['ADDRESS_ID'][i];
anOption.innerHTML = array['ADDRESS_ID'][i];
theSelect.appendChild(anOption);
}
// Add the <div> to the DOM, then add the <select> to the <div>
document.getElementById('container_for_select_container').appendChild(theContainer);
theContainer.appendChild(theSelect);
</script>
<div id="container_for_select_container">
</div>
</body>
</html>
最佳答案
除了一些问题之外,您的代码运行良好。如前所述,您的数组长度是错误的。您需要使用 array['ADDRESS_ID'].length
而不是 array.length
并且您需要将 div
与 id '在 JavaScript 代码之前添加“container_for_select_container”,或者将 JavaScript 代码放入 window.load
函数中。否则,您将尝试将选择框附加到尚不存在的 HTML 元素。
<div id="container_for_select_container"></div>
<script type="text/javascript">
var array = {
"ADDRESS_ID": ["3", "5"],
"ADDRESS_PLACE": ["a", "b"],
"ADDRESS_PARENT": [null, null],
"TYPE": ["0", "1"]
};
var i, theContainer, theSelect, theOptions, numOptions, anOption;
theContainer = document.createElement('div');
theContainer.id = array['TYPE'][0];
theSelect = document.createElement('select');
theSelect.name = 'name_of_select';
theSelect.id = 'id_of_select';
theSelect.onchange = function() {
alert('You selected option ' + this.selectedIndex);
};
// Add some <option>s
numOptions = array['ADDRESS_ID'].length;
for (i = 0; i < numOptions; i++) {
anOption = document.createElement('option');
anOption.value = array['ADDRESS_ID'][i];
anOption.innerHTML = array['ADDRESS_ID'][i];
theSelect.appendChild(anOption);
}
// Add the <div> to the DOM, then add the <select> to the <div>
document.getElementById('container_for_select_container').appendChild(theContainer);
theContainer.appendChild(theSelect);
</script>
关于javascript 无法识别我的 html 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20837921/