1

嗨,想知道您是否可以提供帮助,当用户指定他们的性别类型时,我需要使用 JavaScript 在衣服选项框中填充适当的选项。这是我到目前为止的代码,

<script type="text/javascript">
var subListArray = [];
subListArray[0] = 'Select a type first';
subListArray[1] = ['skirt', 'dress', 'tights'];
subListArray[2] = ['jeans', 'hat'];
</script>

       Gender Type: <select name="genderType" id="genderType" >
      <option value="">Gender Type?</option>
      <option value="girl">Female</option>
      <option value="boy">Male</option>
    </select> </br>

        Clothes <select name="clothType">
      <option value="">Choose a Type</option>
    </select>
4

2 回答 2

1

使用对象而不是数组,以便您可以将 映射subList到选定的性别。您不必这样,但它会简化一些事情。向为新选择框创建选项元素的性别选择器添加一个“更改”侦听器:

var subListArray = {
    'default': ['Select a type first'],
    'girl': ['skirt', 'dress', 'tights'],
    'boy': ['jeans', 'hat'],
};

document.getElementById('genderType').addEventListener('change', function () {
    var sel = document.getElementById('clothType'),
        value = this.value ? this.value : 'default';
    sel.innerHTML = '';
    subListArray[value].forEach(function (item) {
       sel.appendChild(new Option(item));
    });
});

http://jsfiddle.net/VdXk6/

于 2013-03-05T18:16:21.530 回答
0

请参阅此页面,其中解释了向 DOM 添加元素: http ://www.javascriptkit.com/javatutors/dom2.shtml

您需要使用 createElement、setAttribute 和 appendChild。例如:

html:

<select id="mySelect">...</select>
<select id="mySubSelect"></select>

javascript:

var myNewOption = document.createElement( 'option' );
myNewOption.setAttribute( 'value', 'myOptionValue' );
document.getElementById( 'mySubSelect' ).appendChild( myNewOption );

这可以循环进行。您还可以检测选择何时更改,如下所示:

javascript:

document.getElementById('mySelect').addEventListener('change',function(){
    document.getElementById('mySelect').selectedIndex; // a number showing which element is selected
});

使用 jQuery 就容易多了。

于 2013-03-05T18:20:35.117 回答