我正在尝试使用JavaScript jQuery进行下拉列表。使用Zend Framework2和学说,我将HTML元素呈现如下:
<div>
Country<select name="country"><option value="">--select Country-</option>
<option value="1" class="country" id="country">Greater Accra</option>
<option value="2" class="country" id="country">Ashanti</option>
<option value="3" class="country" id="country">Central</option>
<option value="4" class="country" id="country">Eastern</option></select>
</div>
<div>
States<select name="states"><option value="">--select States--</option>
<option value="1" class="states" id="states" data-id="1">Roman Ridge</option>
<option value="2" class="states" id="states" data-id="2">Kumasi</option>
<option value="3" class="states" id="states" data-id="3">Cape Coast</option>
<option value="4" class="states" id="states" data-id="4">Koforidua</option>
<option value="5" class="states" id="states" data-id="1">Accra</option>
<option value="6" class="states" id="states" data-id="3">Moree</option>
<option value="7" class="states" id="states" data-id="1">Chantan</option>
<option value="8" class="states" id="states" data-id="1">Achimota</option>
<option value="9" class="states" id="states" data-id="2">Mampong</option>
<option value="10" class="states" id="states" data-id="1">Lapaz</option></select>
</div>
这是我的jQuery fuction
<script>
$(document).ready(function(){
var s1 = $('#country');
var s2 = $('#states');
var dependantOptions = s2.find('option');
dependantOptions.css('visibility', 'hidden');
s1.on('change', function() {
dependantOptions.css('visibility', 'hidden');
s2.find("option[data-id='" + $(this).val() + "']").css('visibility', 'visible');
});
});
</script>
我无法弄清楚为什么JavaScript函数不起作用。我希望尽快找到答案。谢谢
您的选择列表只有属性name="country"
和name="states"
,并且没有相应的ID。您这样搜索:
var s1 = $('#country');
var s2 = $('#states');
因此,您应该添加IDS id="country"
和id="states"
。