繁体   English   中英

为什么这个JavaScript无法在我的网站上运作?

[英]Why is this javascript not working on my site?

我正在尝试进行级联下拉菜单,在其中应根据国家/地区对状态进行过滤,我尝试了许多与网站无关的代码,当我将其用作单独的演示测试代码并给出根据我的要求返回结果,但是当我在项目中使用相同的代码时,它不起作用。

我的脚本代码如下:

<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>

您的Array有一个用于United States的额外空间。 首先,您需要纠正一个

//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 并且由于将它们定义为诸如state["United State"]state["Indonesia"] ,因此可以使用.hasOwnProperty()方法来检查所选国家/地区是否作为key存在于state数组中。

if (!state.hasOwnProperty(make)) return;

小提琴

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM