繁体   English   中英

为什么这段 JS 代码不能在旧设备上运行?

[英]Why doesn't this JS code run on older devices?

我正在尝试基于 openweathermap API 构建一个简单的 MagicMirror 浏览器内天气应用程序。

对编码知之甚少,事实证明这有点困难。 我有这个代码,有人为我纠正了,但它不会在旧设备上运行。 这是沙盒链接


class Weather {
    constructor(data) {
      this.data = data;
      this.temp = Math.round(data.main.temp);
      this.feels_like = Math.round(data.main.feels_like);
      this.description = data.weather[0].description;
      this.city = data.name;
      this.country = data.sys.country;
      this.wind = Math.round(data.wind.speed);
      this.humidity = data.main.humidity;
    }
  
    geticonClass() {
      let prefix = this.data.weather[0].icon.endsWith("d")
        ? 'wi-owm-day-'
        : 'wi-owm-night-';
      return `${prefix}${this.data.weather[0].id}`;
    }
  }
  
  function fetchWeather() {
    navigator.geolocation.getCurrentPosition(
      async (position) => {
        let url = new URL("https://api.openweathermap.org/data/2.5/weather");
        url.searchParams.set("lat", position.coords.latitude);
        url.searchParams.set("lon", position.coords.longitude);
        url.searchParams.set("lang", "pl");
        url.searchParams.set("appid", "fb7164d50e0faf1f058561b7903f03b9");
        url.searchParams.set("units", "metric");
  
        const response = await fetch(url);
        const weatherJSON = await response.json();
        updateDOM(new Weather(weatherJSON));
      },
      (error) => {
        console.error("Unable to get geolocation, Unsuported maybe?");
      }
    );
  }
  
  function updateDOM(weather) {
    const iconElement = document.querySelector(".today-weather-icon i");
    const tempElement = document.querySelector(".temperature-value p");
    const tempFeelElement = document.querySelector(".temperature-feel p");
    const descElement = document.querySelector(".temperature-description p");
    const locationElement = document.querySelector(".location p");
    const windElement = document.querySelector(".wind p");
    const humidElement = document.querySelector(".humid p");

    iconElement.classList.add(weather.geticonClass());
    tempElement.innerHTML = `${weather.temp}°<span>C</span>`;
    tempFeelElement.innerHTML = `Odczuwalna: ${weather.feels_like}°<span>C</span>`;
    descElement.innerHTML = weather.description;
    locationElement.innerHTML = `${weather.city}, ${weather.country}`;
    windElement.innerHTML = ` ${weather.wind} km/h`;
    humidElement.innerHTML = ` ${weather.humidity}`;
  }
  
  fetchWeather();
  setInterval(fetchWeather, 1800000);
  updateDOM();
  setInterval(updateDOM, 1820000);

这是具有 navigator.geolocation 的以前版本的代码,它可以工作。

您正在使用现代 ES6 语法,例如class Weather这就是原因。 如果您想了解更多关于如何将其转换为 ES6 之前的语法以便它也适用于旧设备的信息,请查看这篇文章ES6 Class 与 Object.prototyoe `

暂无
暂无

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

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