根据下拉选择使用.load填充div

时间:2016-02-29 00:32:38

标签: jquery html ajax drop-down-menu

好吧这感觉像是一件基本的事情,但是我努力让它发挥作用 - 我想要完成的是一个包含大约45个县的下拉列表,当选择一个时,正文中的空div将加载来自另一个html页面的div(我将在其中容纳相应的45个div)位置信息)。

打算使用ajax加载样式事件

<script>
$(document).ready(function(){
        $("#county-result").load("county_list.html #county1");
});
</script>

但是为了减少脚本的重量,我希望下拉值成为匹配的县div id来填充加载函数的那一部分(而不是编写45个单独的部分)

关于我如何做到这一点的想法?

2 个答案:

答案 0 :(得分:1)

我为你创建了一个plunkr!我希望它有所帮助

我在这里基本上做的是,我将一个更改事件监听器添加到选择(下拉列表)并且我确保我的国家/地区html文件中的div与我的主文件中的选项值具有相同的ID(您将拥有下拉菜单的那个)

因此,如果你想了解德国的信息,你必须确保国家选项和div看起来有点像这样

<option value="germany">germany</option>

<div id="germany">
    <h1>Berlin</h1>
</div>

答案 1 :(得分:1)

这个问题有点宽泛。但是,如果我需要处理与45个县相关的信息并需要显示从下拉列表中选择的县的信息,我将使用JSON作为我的数据源并使用模板填充div并迭代JSON对象并寻找所选的id。

下面是一个如何运作的例子。请注意,我实际上是根据数据集本身动态构建选择框选项,并且设置允许您在需要时轻松更新数据。

注意您如何获得JSON取决于您。我已经为此示例对其进行了硬编码,但您可以通过ajax请求或使用.get().load()等来获取它。

&#13;
&#13;
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);
});
&#13;
td,th{
  padding:5px;
}
&#13;
<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>
&#13;
&#13;
&#13;

相关问题