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 に答える