繁体   English   中英

在 HTML 页面显示 LocalStorage

[英]Display LocalStorage on HTML page

我在将 localStorage 中的数据显示到我的 HTML 页面时遇到问题,当我打开控制台时,数据已保存,问题出在 innerhtml 上。 下面是我的 html 和 JS 代码。

当我运行控制台时,我可以看到我的数据保存在 localStorage 上,问题是将该数据输入到页面中

这是我的 html:

    <!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Fizzle</title>
    <link
      rel="stylesheet"
      href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css"
      integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65"
      crossorigin="anonymous"
    />
    <link rel="stylesheet" href="css/style.css" />
    <script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
  </head>
  <body class="">
    <div class="row">
      <div class="col">
        <ul class="workouts">
          <section class="weather">
            <div id="today-container">
              <div class="current-weather">
                 <h3 class="brand">the weather</h3>
              </div>
              <div>
                <h1 class="temp">16&#176;</h1>
                <div class="city-time">
                  <h1 class="name">London</h1>
                  <small>
                    
                    <span class="date">Monday Sep 19</span>
                  </small>
                </div>
            </div>
          </section>
          <form class="form hidden">
            <div class="form__row">
              <label class="form__label">Type</label>
              <select class="form__input form__input--type">
                <option value="running">Running</option>
                <option value="cycling">Cycling</option>
              </select>
            </div>
            <div class="form__row">
              <label class="form__label">Distance</label>
              <input id="distance-input"
                class="form__input form__input--distance"
                placeholder="km"
              />
            </div>
            <div class="form__row">
              <label class="form__label">Duration</label>
              <input id="duration-input" 
                class="form__input form__input--duration"
                placeholder="min"
              />
            </div>


            <div class="form__row">
              <label class="form__label">Elevation</label>
              <input id ="elevation-input" 
                class="form__input form__input--cadence"
                placeholder="meters"
              />
            </div>

            <button class="form__btn">OK</button>
          </form>
        </ul>
      </div>
      <div class="col">
        <div id="map"></div>
      </div>
      <p> <h4 class="ElementThatHoldsTheHistoryData"></h4></p>
    </div>
    <div id="floating-panel"></div>

    <div id="sidebar"></div>

    <script
    src="https://maps.googleapis.com/maps/api/js?key=API Key here"
    defer>
    </script>
    <!-- <script async defer src="https://maps.googleapis.com/maps/api/js?key=APIkey here=initMap&libraries=geometry"></script> -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
    <script src="js/app.js"></script>
  </body>
</html>

这是我的 JS 代码:

enter code her/Get all necessary elements from the DOM

const temp = document.querySelector(".temp");
const dateOutput = document.querySelector(".date");
const timeOutput = document.querySelector(".time");
const distance = document.querySelector("#distance-input");
const duration = document.querySelector("#duration-input");
const elevation = document.querySelector(".form__input--elevation");
const todayContainer = document.querySelector("#today-container");

// set my variables
var currentWeather = document.querySelector(".current-weather");
var APIkey = "&appid=99d1a7e58f500ed377f1399b47f88c6a";
var distanceInput = document.getElementById("distance-input");
var durationInput = document.getElementById("duration-input");
var elevationInput = document.getElementById("elevation-input");
var map;
var markers = [];
var directionsService;
var directionsRenderer;
var workoutElements = document.getElementsByClassName("workout");
var btn = document.querySelector(".form__btn");

//Default city when the page loads/------------------------------------------------------------
let cityInput = "London";

/// Get date /----------------------------------------------------------------------------------------------------------------
const date = moment().format("h:mm a - dddd MMM YY");
dateOutput.innerText = date;
// console.log(date);

// Google map
// map code with 2 markers and directions-----working code------------------------

function initMap() {
  map = new google.maps.Map(document.getElementById("map"), {
    center: { lat: 51.509865, lng: -0.118092 }, //center mapp to Hyde park London
    zoom: 12.5,
  });

  directionsService = new google.maps.DirectionsService();
  directionsRenderer = new google.maps.DirectionsRenderer();
  directionsRenderer.setMap(map);
  directionsRenderer.setOptions({
    polylineOptions: {
      strokeColor: "red",
    },
    suppressMarkers: true,
  });
  // Add a click event listener to the map
  google.maps.event.addListener(map, "click", function (event) {
    addMarker(event.latLng);
  });
}
function addMarker(location) {
  // Add the marker at the clicked location
  var marker = new google.maps.Marker({
    position: location,
    map: map,
  });
  markers.push(marker);
  if (markers.length >= 2) {
    calculateAndDisplayRoute();
  }
}
function deleteMarkers() {
  // Clear markers from the map
  for (var i = 0; i < markers.length; i++) {
    markers[i].setMap(null);
  }
  markers = [];
}
//function to add distance and duration:
function calculateAndDisplayRoute() {
  var request = {
    origin: markers[0].getPosition(),
    destination: markers[1].getPosition(),
    travelMode: "BICYCLING",
    provideRouteAlternatives: true,

    unitSystem: google.maps.UnitSystem.METRIC,
  };
  directionsService.route(request, function (response, status) {
    if (status === "OK") {
      directionsRenderer.setDirections(response);
      var distance = response.routes[0].legs[0].distance.text;
      var duration = response.routes[0].legs[0].duration.text;
      var elevation = response.routes[0].legs[0].elevation;
      // set input values
      document.getElementById("distance-input").value = distance;
      document.getElementById("duration-input").value = duration;
      document.getElementById("elevation-input").value = elevation;
    } else {
      window.alert("Directions request failed due to " + status);
    }
  });
}

function getLocation() {
  navigator.geolocation.getCurrentPosition((data) => {
    const lat = data.coords.latitude;
    const lon = data.coords.longitude;
    initMap(lat, lon);
    currentConditions(lat, lon);
  });
}

//Weather

//fetch data from current weather api, and display desired data on the page
function currentConditions(lat, lon) {
  let currentWeatherAPI = `https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lon}${APIkey}&units=metric`;
  const tempDisplay = document.querySelector(".temp");
  const cityname = document.querySelector(".name");
  fetch(currentWeatherAPI)
    .then(function (response) {
      return response.json();
    })
    .then(function (wdata) {
      // city's name, and use moment to get the date
      // var city = getLocation();

      // weather condition icon
      var weatherIcon = wdata.weather[0].icon;
      //add
      tempDisplay.innerText = Math.round(wdata.main.temp) + "°";
      cityname.innerText = wdata.name;
    });
}

getLocation();

// local storage
btn.addEventListener("click", function (event) {
  event.preventDefault();
  // Clear form
  distance.value = "";
  duration.value = "";

  // Clear markers from the map
  for (var i = 0; i < markers.length; i++) {
    markers[i].setMap(null);
  }
  markers = [];

  var rides = JSON.parse(localStorage.getItem("rides")) || []; // Add new ride to existing rides data in LS
  var newRide = { distance: distance.value, duration: duration.value };
  rides.push(newRide);
  localStorage.setItem("rides", JSON.stringify(rides));

  // for loop to iterate through the collection of elements and set the innerHTML property of each element to the stored data.
  

    var element = document.querySelector("ElementThatHoldsTheHistoryData");
      for (let i = 0; i < rides.length; i++) {
        var h4 = document.createElement("p");
        h4.textContent = `The Distance was ${rides[i].distance} and the Duration was ${rides[i].duration}`;
        element.appendChild(h4);
      }});

像这样安排你的 p 标签

const h4 = `<p>The Distance was ${rides[i].distance} and the Duration was ${rides[i].duration}</p>` 

我宁愿使用 getElementById 或 className 而不是document.querySelector

document.getElementById('question-header').append(h4)

最后把append你的HTML给Id

localstorage运作良好。

[英]localstorage works well.. no need display in same page.. i want display this data into next html page in with div ?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM