我接手了一个小型的网络应用程序。我正在学习JQuery,所以我想用JQuery重写当前的java脚本。这就是我所拥有的 1. xml文件如下
<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>
感谢您的任何提示和帮助。
答案 0 :(得分:4)
这应该让你开始:
<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>
我正在使用$(document).ready();
等待页面准备就绪。一旦它,我将加载文件courses.xml
中的所有数据(您将更改为返回XML文件的任何数据)。获得此数据后,我将使用XML中所有课程的值填充课程<select>
。然后,每次更改课程<select>
时,我都会触发一个触发器。当发生这种情况时,我会找到所选择的课程并循环遍历时间<select>
。
经过测试和工作。