如何动态实现html形式的下拉列表?

存在两个html形式的下拉列表: 第一个名为“国家/地区”的列表包含国家/地区列表; 第二个列表是在选择一个国家时应动态填充的“城市”。 我应该如何动态实现呢?什么是最简单的方法?在javascript还是jquery或ajax中? 请提供示例代码、外部链接或教程,以便我能够实现它。

Using jQuery, use the change event of the first drop down, then update the second, a little like so

$("#country").change(function(){
    //do an ajax request, and update #cities
});

You can do this with pure JavaScript. Implement an onchange attribute in the first select:

<select id="countires" onchange="makeCitiySelect( );"> .. </select

and in the makeCitiySelect( ) function you can read the value of this select with document.getElementsById( "countries" ).value and send create the new select box with the cities of this country.

If the cities of your countries are in a database on the server you have to send an ajax request and get the cities as response..

But for sure, with jQuery you can solve this problem much better

1.- Create the 2 select boxes 2.- Create an onchange js or jquery function on the first select, so every time it gets selected the other select changes 3.- Inside the onchange function make an ajax call to the service which has the corresponding contents for the selected option. 4.- Retrieve the data and rebuild the second select box with the corresponding data.

  1. Apply a onchange event on your country dropdown (http://api.jquery.com/change/)
  2. Send an ajax request to server and get the city list (http://api.jquery.com/jQuery.ajax/)
  3. On success of ajax request, populate the second list "cities". Remember to remove any already populated cities from the cities list.
  4. Store all the cities list which you got from server into an array. When next time the users selects the same country, use data stored in array to display the cities list. This way you don't have to make multiple ajax request for same country.