首页 > 解决方案 > 如何设置喜欢的用户搜索输入?JS

问题描述

我正在开发我的天气网络应用程序。当用户在搜索栏中输入他的城市时,应用程序会显示 5 天的预测。需要设置按钮将城市保存在浏览器存储或cookie中。当用户刷新网页时,自动加载他喜欢的城市。

这是我的html:

<div id="search">
    <input type="text" id="serach-city-input">
    <a id="search-city-button" class="btn btn-danger">Search</a>
</div>

以及用于连接 API 的 JS:

$('#search-city-button').on('click', () => {
    const searchString = $('#serach-city-input').val();
    weatherPage.render(searchString);
    weatherPage.renderThreeHours(searchString);
});

标签: javascriptcookies

解决方案


单击按钮保存时,您应该使用localStorage.setItem('favoriteCity', searchString)保存用户的值。
然后,当您加载页面时,使用localStorage.getItem('favoriteCity')检索保存的值。您应该有一个方法 Init() 或使用您的方法render(localStorage.getItem('favoriteCity'))


推荐阅读