【问题标题】:Javascript to populate an option box with an array用数组填充选项框的 Javascript
【发布时间】:2013-02-20 06:44:46
【问题描述】:

您好,想知道您是否可以提供帮助,当用户指定他们的性别类型时,我需要使用 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>

【问题讨论】:

  • 你如何将性别与特定的数组联系起来?
  • 你是不是建议男人不要穿tights? :P
  • @Jason:Cary Elwes 让它看起来不错,这是真的。
  • 我不知道如何将性别与特定数组联系起来,我只是想要它,所以当您选择性别类型的女孩时,“裙子”、“连衣裙”、“紧身衣”会出现在选项值中在衣服上。

标签: javascript arrays option


【解决方案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/

【讨论】:

  • 无论如何我都不应该改变数组。我是否只是将默认值,女孩,男孩改回 subListArray[0] subListArray[1] subListArray[2]?
  • @user2136922 应该很简单;只需检查if value == 'boy' 然后使用subListArray[2] 等。
  • 我在哪里把它放在代码中,我用什么替换它?谢谢
  • @user2136922 把它放在&lt;/body&gt; 之前。替换它是什么意思?
  • 我的意思是如果我把 if 语句放入我需要更改我使用的任何代码吗?你可以添加它吗,因为我不太擅长这个?谢谢
【解决方案2】:

请参阅此页面,该页面解释了向 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 会容易得多。

【讨论】:

  • 请不要推荐内联javascript事件处理程序。
猜你喜欢
  • 2019-10-08
  • 1970-01-01
  • 1970-01-01
  • 2021-03-05
  • 1970-01-01
  • 2011-09-25
  • 2013-03-10
  • 2015-11-20
  • 1970-01-01
相关资源
最近更新 更多