动态加载数据从xml到带有jQuery的下拉框 [英] dynamic load data from xml to drop down box with jquery
问题描述
我接管了一个小型Web应用程序。我正在学习JQuery,所以我想用JQuery重写当前的Java脚本。这就是我的
1. xml文件如下
I took over a small web application. I am learning JQuery so I like to rewrite the current java script with JQuery. Here is what I have 1. the xml file as following
<courses>
<course title="math">
<time>1:00pm</time>
<time>3:00pm</time>
</course>
<course title="physic">
<time>1:00pm</time>
<time>3:00pm</time>
</course>
</courses>
- 我想加载下拉box1
- 从box1中选择标题时,下拉box2将填写对标题的响应时间。
感谢任何提示和帮助。
推荐答案
这应该使您入门:
<script type="text/javascript">
$(document).ready(function() {
var course_data; // variable to hold data in once it is loaded
$.get('courses.xml', function(data) { // get the courses.xml file
course_data = data; // save the data for future use
// so we don't have to call the file again
var that = $('#courses'); // that = the courses select
$('course', course_data).each(function() { // find courses in data
// dynamically create a new option element
// make its text the value of the "title" attribute in the XML
// and append it to the courses select
$('<option>').text($(this).attr('title')).appendTo(that);
});
}, 'xml'); // specify what format the request will return - XML
$('#courses').change(function() { // bind a trigger to when the
// courses select changes
var val = $(this).val(); // hold the select's new value
var that = $('#times').empty(); // empty the select of times
// and hold a reference in 'that'
$('course', course_data).filter(function() { // get all courses...
return val == $(this).attr('title'); // find the one chosen
}).find('time').each(function() { // find all the times...
// create a new option, set its text to the time, append to
// the times select
$('<option>').text($(this).text()).appendTo(that);
});
});
});
</script>
Courses:
<select id='courses'>
<option value='0'>----------</option>
</select>
<br>
Times:
<select id='times'>
<option value='0'>----------</option>
</select>
它在做什么:
I正在使用 $(document).ready();
等待页面准备就绪。一旦完成,我将从文件 courses.xml
(您将更改为返回XML文件的任何内容)中加载所有数据。获得此数据后,将使用XML中所有课程的值填充课程< select>
。然后,我绑定触发器以在每次更改课程< select>
时触发。发生这种情况时,我会找到已选择的课程,并遍历所有时间,将其添加到时间< select>
。
What it is doing:
I am using $(document).ready();
to wait until the page is ready. Once it is, I am loading all the data from the file courses.xml
(which you would change to whatever returns your XML file). Once I get this data, I populate the courses <select>
with the value of all the courses in the XML. I then bind a trigger to fire everytime the courses <select>
is changed. When this happens, I find the course which was selected and loop through all its times appending them to the times <select>
.
经过测试并可以工作。
这篇关于动态加载数据从xml到带有jQuery的下拉框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!