[英]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.