[英]Populate div with .load based on drop down selection
好吧,这听起来像是一件基本的事情,但是我很难做到这一点-我要完成的工作是在下拉列表中列出约45个县,当选中一个县时,主体中的一个空div将加载来自另一个html页面(我将在其中放置45 div的相应位置信息)。
打算使用ajax加载样式事件
<script>
$(document).ready(function(){
$("#county-result").load("county_list.html #county1");
});
</script>
但是,为了使脚本不那么沉重,我希望下拉列表值为与其匹配的County div id,以填充部分加载函数(而不是编写45个独立的div)
关于如何执行此操作的想法?
这个问题有点广泛。 但是,如果我需要处理与45个县相关的信息,并且需要显示从下拉列表中选择的县的信息,则可以使用JSON作为数据源,并使用模板填充div并遍历JSON对象,寻找所选的ID。
下面是一个示例,说明如何工作。 请注意,我实际上是根据数据集本身动态构建选择框选项,并且该设置使您可以根据需要轻松地更新数据。
请注意,如何获取JSON取决于您。 在本示例中,我已经对其进行了硬编码,但是您可以通过ajax请求或使用.get()
.load()
等获取它。
var myCountyInfo = { counties: [{ name: 'County 1', id:123, locationInfo: { lat: 453245, lng: 45545, avgTemp: '75f', population: '5 B.' } }, { name: 'County 2', id:456, locationInfo: { lat: 11221, lng: 542222, avgTemp: '59f', population: '2 B.' } }, { name: 'County 3', id:789, locationInfo: { lat: 88555, lng: 54757, avgTemp: '58f', population: '1 B.' } }] } function populateSelectBoxes($select, data) { var counties = []; $.each(data, function() { counties.push('<option value="'+this.id+'">' + this.name + '</option>'); }); $select.append(counties.join('')); } function populateTableRow($tableBody, data, selectedCountyId) { var county; $.each(data, function() { if (this.id == selectedCountyId) { county = this; return false; } }); $tableBody.html('<tr>'+ '<td>' + county.name + '</td>'+ '<td>' + county.locationInfo.lat +'</td>'+ '<td>' + county.locationInfo.lng + '</td>'+ '<td>' + county.locationInfo.avgTemp + '</td>'+ '<td>' + county.locationInfo.population + '</td>'+ '</tr>'); } populateSelectBoxes($('#my-select'), myCountyInfo.counties); $('#my-select').change(function() { var $this = $(this); var selection = $this.val(); populateTableRow($('#my-table tbody'), myCountyInfo.counties, selection); });
td,th{ padding:5px; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <select name="" id="my-select"></select> <table id="my-table" border="1"> <thead> <tr> <th>County</th> <th>Lat.</th> <th>Lng.</th> <th>Avg Temp</th> <th>Population</th> </tr> </thead> <tbody> </tbody> </table>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.