动态组合框javascript

时间:2011-08-18 12:32:06

标签: javascript

我正在尝试在javascript中创建一个组合框并从数组中填充它。在选择时,我想要更改变量,调用函数等。我已经在线查看了多个教程,但是对于这么简单的任务,教程是可怕的。

有人可以帮忙吗? 干杯

1 个答案:

答案 0 :(得分:5)

var i, theContainer, theSelect, theOptions, numOptions, anOption;
theOptions = ['option 1','option 2','option 3'];

// Create the container <div>
theContainer = document.createElement('div');
theContainer.id = 'my_new_div';

// Create the <select>
theSelect = document.createElement('select');

// Give the <select> some attributes
theSelect.name = 'name_of_select';
theSelect.id = 'id_of_select';
theSelect.className = 'class_of_select';

// Define something to do onChange
theSelect.onchange = function () {
    // Do whatever you want to do when the select changes
    alert('You selected option '+this.selectedIndex);
};

// Add some <option>s
numOptions = theOptions.length;
for (i = 0; i < numOptions; i++) {
    anOption = document.createElement('option');
    anOption.value = i;
    anOption.innerHTML = theOptions[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);