我尝试使用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>
答案 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
});
}