首页 > 解决方案 > 将点击事件更改为页面加载

问题描述

我有一个天气 api 的演示代码。我需要将它从点击事件更改为在页面打开时加载。我该怎么做。我对 jquery 还很陌生。欢迎任何帮助

function bclicked() 
{ 
    //This function was for testing my button and containers
    console.log("CLICKED!");
    var node = document.createElement("P");
    var textnode = document.createTextNode("Placeholder for real weather!");
    node.appendChild(textnode);
    document.getElementById("weather").innerHTML = "";
    document.getElementById("weather").appendChild(node);
}

function getweather() 
{ 
    //Does a post request for the ZIP entered to the API
    console.log("REQUESTING WEATHER");
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function () 
    {
        if (this.readyState == 4 && this.status == 200) {
            var weather = JSON.parse(this.responseText);
            console.log(weather);
            maketable(weather); //Generates content
        }
        else
        { 
            console.log("this.readyState=",this.readyState);
            console.log("this.status=",this.status);
        }
    };

    var dataprefix = "https://api.openweathermap.org/data/2.5/weather?zip=33431,us"
    var datasuffix = "&units=imperial&appid=925e764bc4519818e577ebdbae087ef8"
    var data = dataprefix + document.getElementById.value + datasuffix;
    console.log("requesting:",data);
    xmlhttp.open("POST", data, true)
    xmlhttp.send();
}

标签: jquery

解决方案


删除该函数bclicked(),然后调用getweather()如下。这将getweather()在页面加载时调用函数。

getweather();

function getweather() 
{ 
    // function body
}

推荐阅读