微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用jquery从xml动态加载数据到下拉框

我接手了一个小型的网络应用程序.我正在学习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>

>我喜欢加载到标题下拉框1.
>当从Box1中选择标题时,下拉框2将填写对标题的响应时间.

感谢您的任何提示和帮助.

解决方法

这应该让你开始:
<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文件的任何数据).获得此数据后,我会填充课程< select>具有XML中所有课程的价值.然后我绑定一个触发器,每当课程< select>改变了.当发生这种情况时,我会找到所选择的课程并循环遍历时间< select>.

经过测试和工作.

原文地址:https://www.jb51.cc/jquery/180810.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐