gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 03:45:08 24 4
gpt4 key购买 nike

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

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

我现在面临的问题是,目前我已将所有服务框元素放入第一个包装器中。有没有办法将服务框元素插入到正确的 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();

}

最佳答案

findNearestStation ,代码serviceResultsWrapper[0].innerHTML += serviceBoxTemplate;将服务框插入 div.service-results-wrapper 第一个 div.result 。您应该将该代码替换为如下内容:

let currentWrapper = [...serviceResultsWrapper].find((wrapper) => wrapper.dataset.stationcode === currentStationCode);
let serviceBoxFragment = document.createRange().createContextualFragment(serviceBoxTemplate);

currentWrapper.appendChild(serviceBoxFragment);

关于javascript - 使用 javascript 将基于动态值的多个 html 元素插入到不同的 DIV 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45426534/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com