使用javascript将基于动态值的多个html元素插入到不同的DIV中

时间:2017-07-31 22:59:43

标签: javascript api

我在弄清楚我需要做什么时遇到了一些麻烦。

我在一个小火车时刻表应用程序上工作,找到五个最近的车站并显示所有五个车站的时刻表。我已成功找到最近的车站,并设法从每个车站获得所有服务信息。我在每个工作站的包装元素上使用了数据集,作为向每个包装器插入正确服务信息的方法。

我现在面临的问题是,目前我已将所有服务盒元素放入第一个包装器中。有没有办法将服务框元素插入到正确的DIV中?

我正在使用的API提供了一个独特的3字符站代码(例如FST等),以及我用来查找附近站点的API。

例如,我有5个站,代码为AAA,AAB,AAC,AAD和AAE。应使用AAA数据集将所有AAA站插入相应的DIV,与AAB等相同......

如果您需要了解,我正在使用TransportAPI。

查看我到目前为止的Javascript代码。提前谢谢。

// scripts

// change protocol to https if http
if (window.location.protocol != 'https:') window.location.protocol = 'https';

// 
var info = document.querySelector(".info");

// check if geolocation works/is supported using if statement
// if geolocation is supported
if ("geolocation" in navigator) {

    // log to console
    console.log("GeoLocation is working.");

    // function to run if geolocation is supported
    navigator.geolocation.getCurrentPosition(function(position) {

        // store users coords
        var lat = position.coords.latitude;
        var lon = position.coords.longitude;

        // log them to console
        console.log("Your coordinates are: " + lat + "," + lon);

        // callback function to use users coordinates in another function
        findNearestStation(lat, lon);

    });

    // if geolocation is not supported
} else {

    // log to console
    console.log("GeoLocation is not supported.");
}

function findNearestStation(lat, lon) {

    console.log("Your coordinates are: " + lat + "," + lon);

    // api keys and tokens
    var appID = "xxxxx";
    var appKey = "xxxxxxxxxxxx";

    // api for nearest stations url template
    var transportApiUrl = "https://transportapi.com/v3/uk/train/stations/near.json?app_id=" + appID + "&app_key=" + appKey + "&lat=" + lat + "&lon=" + lon + "&rpp=5";

    // ajax request to get nearest stations
    var nearbyStationsReq = new XMLHttpRequest();

    nearbyStationsReq.open('GET', transportApiUrl, true);

    nearbyStationsReq.onload = function() {

        // results window
        var resultsWindow = document.querySelector(".results-window");

        // empty array for the timetable urls
        var timetableUrlArray = [];
        // empty array for station codes
        var stationCodeArray = [];

        // clear the results window
        resultsWindow.innerHTML = "";

        if (this.status >= 200 && this.status < 400) {
            // response data
            var res = JSON.parse(this.response);

            // variable for stations array in response
            var data = res.stations;

            // for loop to iterate through response data
            for (var i = 0; i < data.length; i++) {

                // get information from response data
                var code = data[i].station_code;
                var name = data[i].name;
                var distanceMetres = data[i].distance;
                var distanceKilometres = (distanceMetres / 1000).toFixed(1);
                var distanceKilometres = distanceKilometres + "km";

                // log data to console to reference
                console.log("Code: " + code + " | Name: " + name + " | Distance: " + distanceKilometres);

                // generate urls for timetable data
                var timetableUrl = "https://transportapi.com/v3/uk/train/station/" + code + "/live.json?app_id=" + appID + "&app_key=" + appKey + "&darwin=true&train_status=passenger";

                // push completed urls to the array
                timetableUrlArray.push(timetableUrl);

                // push codes to empty array
                stationCodeArray.push(code);

                // template for nearest stations result container
                var resultTemplate =
                    "<div class='result'>" +
                    "<div class='station-name'>" +
                    "<span class='service-origin'>" +
                    "<span class='nr-logo'>" +
                    "<img src='assets/images/nr.svg' alt='National Rail Logo'></span>" + name + "</span>" +
                    "</div>" +
                    "<div class='service-results-wrapper' data-stationcode='" + code + "'></div>" +
                    "</div>";

                // insert template in to the results window
                resultsWindow.innerHTML += resultTemplate;

            }

            // log to console
            console.log(stationCodeArray)

            // for loop to create a request for each station
            for (var i = 0; i < timetableUrlArray.length; i++) {

                // ajax request for timetable request
                var timetableReq = new XMLHttpRequest();
                timetableReq.open('GET', timetableUrlArray[i], true);

                timetableReq.onload = function() {
                    if (this.status >= 200 && this.status < 400) {
                        // response from request
                        var res = JSON.parse(this.response);

                        // data for timetable info
                        var data = res.departures.all;

                        // declare service results wrapper
                        var serviceResultsWrapper = document.querySelectorAll(".service-results-wrapper");

                        // loop to go through the data
                        for (var i = 0; i < data.length; i++) {

                            // information required
                            var currentStation = res.station_name;
                            var currentStationCode = res.station_code;
                            var aimedDepartTime = data[i].aimed_departure_time;
                            var expectedDepartTime = data[i].expected_departure_time;
                            var destination = data[i].destination_name;
                            var platform = data[i].platform;
                            var operator = data[i].operator_name;
                            var status = data[i].status;
                            var trainUID = data[i].train_uid;

                            // log data to console
                            console.log("Current Station: " + currentStation + " | Current Station Code: " + currentStationCode + " | Aimed: " + aimedDepartTime + " | Expected: " + expectedDepartTime + " | Destination: " + destination + " | Platform: " + platform + " | Status: " + status + " | Operator: " + operator + " | ID: " + trainUID);

                            // template for service boxes
                            var serviceBoxTemplate = "<span class='service-box'><span class='service-time-status'><span class='service-depart-time'>" + aimedDepartTime + "</span>" +
                                "<span class='service-depart-status'>" + currentStation + "</span>" +
                                "<span class='service-depart-platform'>Plat. <span class='service-platform-number'>" + platform + "</span></span></span>" +
                                "<span class='service-destination'><span class='service-destination-name'>" + destination + "</span></span>" +
                                "<span class='calling stations'>Leigh-on-Sea, Chalkwell, Westcliff, Southend Central, Southend East, Thorpe Bay, Shoeburyness</span>" +
                                "<span class='service-operator'>Operated by <span class='service-operator-by'>" + operator + "</span></div>";

                            serviceResultsWrapper[0].innerHTML += serviceBoxTemplate;

                        }

                    } else {
                        // We reached our target server, but it returned an error

                    }
                };

                timetableReq.onerror = function() {
                    // There was a connection error of some sort
                };

                timetableReq.send();

            }

        } else {
            // log to console
            console.log("There is an error.");

        }
    };

    nearbyStationsReq.onerror = function() {

        // log to console
        console.log("There is an error.");


    };

    nearbyStationsReq.send();

}

1 个答案:

答案 0 :(得分:1)

findNearestStation中,代码serviceResultsWrapper[0].innerHTML += serviceBoxTemplate;会将服务框插入第一个 div.service-results-wrapper的{​​{1}}。您应该使用以下内容替换该代码:

div.result