如何设置喜欢的用户搜索输入? JS

时间:2019-03-20 09:44:46

标签: javascript cookies

我正在开发天气Web应用程序。当用户在搜索栏中输入城市名称时,该应用会显示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);
});

2 个答案:

答案 0 :(得分:0)

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

的方法

答案 1 :(得分:0)

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

function fillValueFromStorege() {
  const storagedValue = localStorage.getItem('serach-city-input');
  if (storagedValue) {
    $('#serach-city-input').val(storagedValue);
    $('#search-city-button').click()
  }
}

fillValueFromStorege()
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="search">
    <input type="text" id="serach-city-input">
    <a id="search-city-button" class="btn btn-danger">Search</a>
</div>

相关问题