我试图在循环中动态插入元素,根据数据集值插入相应的DIV。基本上,如果两个元素具有匹配的数据集值,则应将其插入到特定的div中。
数据集值是唯一的,但在某些情况下,数据集值可能会出现多次。
我在我正在进行的项目的另一部分中使用了以下代码,但是我似乎无法使其适用于我需要做的下一件事。
var callingPointsWrapper = document.querySelectorAll(".callingstations");
var currentCallingWrapper = [...callingPointsWrapper].find((wrapper) => wrapper.dataset.callingpointsid === trainUID);
var callingWrapperFragment = document.createRange().createContextualFragment(callingPointsTemplate);
// add to correct element
callingPointsWrapper.appendChild(callingPointsTemplate);
我的所有代码都在上下文中显示。提前谢谢。
// 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.");
}
// empty array for timetable information
var serviceUrlArray = [];
function findNearestStation(lat, lon) {
// log to console
// console.log("Your coordinates are: " + lat + "," + lon);
// api keys and tokens
var appID = "xxx";
var appKey = "xxxxxx";
// 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;
// generate url
var serviceURL = "https://transportapi.com/v3/uk/train/service/train_uid:" + trainUID + "///timetable.json?app_id=" + appID + "&app_key=" + appKey + "&darwin=true&live=true"
// 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 + " | URL: " + serviceURL);
// if platform is null
if (platform === null) {
// change variable to string
var platform = "n/a";
}
// switch statement to change styling based on status
switch (status) {
case "EARLY":
var status = '<span class="status ontime">On time</span>';
break;
case "ON TIME":
var status = '<span class="status ontime">On time</span>';
break;
case "LATE":
var status = '<span class="status delayed">Delayed' + " " + expectedDepartTime + '</span>';
var aimedDepartTime = '<span class="time unavailable strikethrough">' + aimedDepartTime + '</span>';
break;
case "CANCELLED":
var status = '<span class="status cancelled">Cancelled</span>';
break;
case "NO REPORT":
var status = '<span class="status unavailable">Unavailable</span>';
break;
case "STARTS HERE":
var status = '<span class="status ontime">On time</span>';
break;
case "OFF ROUTE":
var status = '<span class="status unavailable">Unavailable</span>';
break;
case "CHANGE OF ORIGIN":
var status = '<span class="status unavailable">Unavailable</span>';
break;
default:
var status = '<span class="status unavailable">Unavailable</span>';
}
// template for service boxes
var serviceBoxTemplate = "<span class='service-box' data-station='" + currentStationCode + "' data-uid='" + trainUID + "'><span class='service-time-status'><span class='service-depart-time'>" + aimedDepartTime + "</span>" +
status +
"<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='callingstations' data-callingpointsid='" + trainUID + "'>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>";
// inserts correct service in to correct station element based on matching codes
var currentWrapper = [...serviceResultsWrapper].find((wrapper) => wrapper.dataset.stationcode === currentStationCode);
var serviceBoxFragment = document.createRange().createContextualFragment(serviceBoxTemplate);
// add to correct element
currentWrapper.appendChild(serviceBoxFragment);
// ajax request to get service info
var serviceReq = new XMLHttpRequest();
serviceReq.open('GET', serviceURL, true);
serviceReq.onload = function() {
if (this.status >= 200 && this.status < 400) {
// response text
var res = JSON.parse(this.response);
// get array within response text
var data = res.stops;
// get the trains UID
var trainUID = res.train_uid;
// var currentStation = res.station_name;
// new array for calling points
var callingPointsArray = [];
for (var i = 0; i < data.length; i++) {
// get the calling points station names
var callingPoint = data[i].station_name;
// push names in to an array
callingPointsArray.push(callingPoint);
// create a string and add a comma between each name
var callingPointStr = callingPointsArray.join(", ");
// split the array where the calling
var subsequentCallingPoints = callingPointStr.split(currentStation);
var callingPointsTemplate = "<span>" + subsequentCallingPoints + "</span>";
subsequentCallingPoints[1].substring(1).trim()
}
var callingPointsWrapper = document.querySelectorAll(".callingstations");
var currentCallingWrapper = [...callingPointsWrapper].find((wrapper) => wrapper.dataset.callingpointsid === trainUID);
var callingWrapperFragment = document.createRange().createContextualFragment(callingPointsTemplate);
// add to correct element
callingPointsWrapper.appendChild(callingPointsTemplate);
// // add to correct element
// currentWrapper.appendChild(callingPointsFragment);
// callingPointsWrapper[0].innerHTML = "";
// callingPointsWrapper[0].innerHTML = subsequentCallingPoints[1].substring(1).trim();
// console.log(callingPointsArray)
} else {
// We reached our target server, but it returned an error
}
};
serviceReq.onerror = function() {
// There was a connection error of some sort
};
serviceReq.send();
}
// console.log(serviceUrlArray)
} 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();
}
// var request = new XMLHttpRequest();
// request.open('GET', '/my/url', true);
// request.onload = function() {
// if (this.status >= 200 && this.status < 400) {
// // Success!
// var data = JSON.parse(this.response);
// } else {
// // We reached our target server, but it returned an error
// }
// };
// request.onerror = function() {
// // There was a connection error of some sort
// };
// request.send();
// x
&#13;