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