问题描述
所以我想做的是制作一个动态的小脚本来选择countys然后选择城市。好吧,我在mysql数据库中拥有所有的countys和citys。如果我在< select>
标记中选择一个县,则与该县相关的城市应显示在下一个< select>
标签。
So what I want to do is to make a dynamic little script for selecting countys and then cities. Well I have all the countys and citys in a mysql database. If I choose a county in a <select>
tag the cities related to the county should appear in the next <select>
tag.
所以基本上也许我可以做类似的事情
So basically maybe I could do something like
$(document).ready(function() {
$('.county').click(function(){
$(this.name).toggle();
});
});
其中countys的选项可能如下所示:
where the option for countys maybe look something like this:
<option value="This County" name="This County" class="county">This County</option>
当我点击上面的内容时,每个城市都连接到This County。只需要对此进行一些罚款。有人认为他们可以提供帮助吗?
When I click this above then every city connected to "This County"
should appear. Just need some fining in this. Anyone think they can help?
推荐答案
如果页面上的所有内容都是以的形式选择
然后你可以使用county选项的值来显示正确的 select
。
If everything is already on the page in the form of select
then you could use the value of the county option to show up the correct select
.
$("#counties").change(function(){
$(".cities").hide();
$("#" + this.value + "-cities").show();
});
这个工作的例子:
但是,我建议不要这样做,因为它是不是很好。即使您只需要很少的金额,您的页面上也会有每个城市。最好的选择是填充您的县列表,然后使用您自己的JSON和方法。
However, I'd recommend against this since it's not great. You'll have every single city on your page even when you only need a small amount. The best option would be to populate your counties list and then populate the cities on the fly with your own JSON and the $.get() method.
例如(我只是使用,你可以用你自己的数据代替);
For example (I'm just using GeoNames here, you'll substitute with your own data);
$.get('http://ws.geonames.org/countryInfoJSON', function(data) {
$.each(data.geonames, function(i, item) {
$("#countries").append("<option value='" + item.geonameId + "'>" + item.countryName + "</option>");
});
});
$("#countries").change(function() {
$("#cities").empty();
$.get('http://ws.geonames.org/childrenJSON?geonameId=' + this.value, function(data) {
$.each(data.geonames, function(i, item) {
$("#cities").append("<option value='" + item.geonameId + "'>" + item.name + "</option>");
});
});
});
工作示例:
以上加载国家/地区并设置更改事件国家
选择。当此值更改时,它将使用所需数据进入服务器。在这种情况下,它会发送 geonameId
并查找该国家/地区的子元素。然后它清除 cities
选择并添加AJAX请求中返回的城市。
The above loads the countries and sets the change event of the countries
select. When this value changes, it goes off to the server with the data needed. In this case, it sends off the geonameId
and finds the child elements of that country. It then clears the cities
select and adds the cities returned in the AJAX request.
这样做的好处是你只需加载你需要的东西,免于必须在页面加载上发送所有数据。我在示例中使用GeoNames,但如果您有自己的数据集,那么基本原则是相同的。
The benefit of this is that you only load what you need, saving yourself from having to send all the data on the page load. I use GeoNames in the example but if you have your own dataset then the basic principles are the same.
这篇关于如何动态切换jquery中的元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!