选择选项:使用Ajax显示更改时的选定值

时间:2016-06-15 05:21:24

标签: jquery ajax

我尝试使用Ajax在select文件中显示数据。 我有一份足球联赛名单。选中后,我希望league.html中的数据显示在#league-display内。

我还想在#league-display内默认显示第一个选项的值。请帮助..

<select name="league">
<option value="premiere-league">Premiere League</option>
<option value="champions-league">Champions League</option>
<option value="laliga">La Liga</option>
<option value="bundesliga">Bundesliga</option>
</select>
<div id="league-display"></div>

以下是league.html内容

<div id="league-details">
 <div id="premiere-league">
   Data of Premiere League
 </div>
 <div id="champions-league">
   Data of Champions League
 </div>
 <div id="laliga">
   Data of La Liga
 </div>
 <div id="bundesliga">
   Data of Bundesliga League
 </div>
</div>

1 个答案:

答案 0 :(得分:1)

change撰写select个活动,并使用 $.load 加载html页面的具体位置。请考虑以下示例

<select name="league">
     <option value="premiere-league">Premiere League</option>
     <option value="champions-league">Champions League</option>
     <option value="laliga">La Liga</option>
     <option value="bundesliga">Bundesliga</option>
</select>
<div id="league-display"></div>

<强> JS

$('select[name="league"]').on('change',function(){
  var url="league.html#"+this.value; //construct url and fetch only part of page
  $("#league-display").load(url,function(){
      //Anything you want do after contents are loaded
  });
})

在页面加载时,如果要显示当前选定的数据,请再次使用相同的load功能。为了做得更好,你可以在function内移动你的装载物并相应地调用它。

$(document).ready(function(){
   loadData(); //call the function
});

$('select[name="league"]').on('change',loadData); //assign the function to the change event

function loadData(){
    var url=$('select[name="league"] option:selected').val();
    $("#league-display").load(url,function(){
       //Anything you want do after contents are loaded
    });
}