динамическая загрузка данных из xml в выпадающий список с помощью jquery - PullRequest
1 голос
/ 17 марта 2009

Я взял небольшое веб-приложение. Я изучаю JQuery, поэтому мне нравится переписывать текущий сценарий Java с JQuery. Вот что у меня 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. Мне нравится загружать выпадающее окно1 с заголовком.
  2. при выборе заголовка из поля1, раскрывающийся список2 заполнит время ответа на заголовок.

Спасибо за любые советы и подсказки.

1 Ответ

4 голосов
/ 17 марта 2009

Это должно помочь вам начать:

<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>.

Проверено и работает.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...