为什么这个javascript无法在我的网站上运行?

时间:2014-04-22 06:13:08

标签: javascript drop-down-menu

我正在努力制作级联下拉列表,其中状态应根据国家/地区进行过滤,我尝试了许多代码,无法使用我的网站,我使用的代码中的一个是正确的工作,当我将其用作单独的演示测试时代码并根据我的要求给出结果但是当我在我的项目中使用相同的代码时它不起作用。

我的脚本代码如下:

<script type="text/javascript">
    var country = new Array('United State','Indonesia','Thailand','Australia','Germany','Japan');
    var state = new Array();
    state["United State"] = new Array("qw", "we", "er", "rt");
    state["Indonesia"] = new Array("as", "sd", "df");
    function resetForm(theForm) {
        /* reset country */
        theForm.country.options[0] = new Option("Please select a country", "");
        for (var i=0; i<country.length; i++) {
        theForm.country.options[i+1] = new Option(country[i], country[i]);
        }
        theForm.country.options[0].selected = true;
        /* reset state */
        theForm.state.options[0] = new Option("Please select a state", "");
        theForm.state.options[0].selected = true;
    }
    function updatestate(theForm) {
        var make = theForm.country.options[theForm.country.options.selectedIndex].value;
        var newstate = state[make];
        theForm.state.options.length = 0;
        theForm.state.options[0] = new Option("Please select a state", "");
        for (var i=0; i<newstate.length; i++) {
            theForm.state.options[i+1] = new Option(newstate[i], newstate[i]);
        }
        theForm.state.options[0].selected = true;
    }
</script>

我的HTML代码也在下面:

<form method="get" name="autoSelectForm">
    <div class="control-group">
        <label>COUNTRY<span style="font-size:13px;font-weight:normal;display:none;">(Max.2)</span></label>
        <select name="country" size="2" style="width:100%; height:25px;" class="choseninput" id="filCountry" onchange="updatestate(this.form)"></select>
    </div>
    <div class="control-group">
        <label>STATE <span style="font-size:13px;font-weight:normal;display:none;">(Max.2)</span></label>
        <select name="state" style="width:100%; height:25px;" class="choseninput" id="filState"></select>
    </div>
<form>

1 个答案:

答案 0 :(得分:0)

Array为您提供额外的美国空间。首先,你需要纠正那个

//var country = new Array('United      State','Indonesia','Thailand','Australia','Germany','Japan');
var country = new Array('United State','Indonesia','Thailand','Australia','Germany','Japan');

您需要做的是在代码中填充状态options之前,您需要检查是否在state数组中为所选country定义了状态。由于您将其定义为state["United State"]state["Indonesia"]等关键字,因此您可以使用.hasOwnProperty()方法检查state数组中所选国家/地区是否存在{{1 }}

key

<强> FIDDLE