现在已实现基本的2个html页面:
首页查询页,会在输入框输入内容,点击查询,列出查询结果,点击后进入

详情页,显示详情,可以点击左上角返回:

现在返回首页时是空的:

希望实现:
能保持之前的数据:
输入的查询内容,以及搜索出结果
另外注意到:
手机的微信中,用取消键返回,不是点击左上角返回按钮,则是可以保留输入框的内容的:

所以这两种方式,最好都支持,能接着自动查询,省去用户手动点击
【总结】
最后是用了localStorage,保存,删除,恢复
代码是:
js/main.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | console.log( "restoreInputAndSearch" ) var curInputValue = $( "#inputQuery" ).val() console.log( "curInputValue=%s" , curInputValue) if (curInputValue){ ajaxSubmitQuery() } else { var preSavedInput = restoreInput() console.log( "preSavedInput=%s" , preSavedInput) if (preSavedInput) { $( "#inputQuery" ).val(preSavedInput) console.log( "Have restored previous saved search input value: %s" , preSavedInput) ajaxSubmitQuery() } } } restoreInputAndSearch() ... $( '.form-clear' ).on( 'click' , function() { $(this).addClass( 'd-none' ).prevAll( ':input' ).val(''); console.log( "has clear input" ) clearInput() }); function ajaxSubmitQuery() { ... storeInput(trimedQuery) |
js/book_common.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | const LastSearchInputStoreKey = "last_search_input" function storeInput(inputStr){ console.log( "storeInput: inputStr=%s" , inputStr) localStorage.setItem(LastSearchInputStoreKey, inputStr) } function restoreInput(){ var savedSearchInput = localStorage.getItem(LastSearchInputStoreKey) console.log( "savedSearchInput=" , savedSearchInput) return savedSearchInput } function clearInput(){ localStorage.removeItem(LastSearchInputStoreKey) } |
效果是:
当输入内容点击查询后,可以保存输入内容到localStorage:

当进入下一页再返回时,localStorage的值还是在的:

然后点击详情页中的返回按钮或点击 浏览器的返回:

然后主页中由于可以检测到 输入框中已经有了内容,所以会触发搜索:

或者从保存的输入恢复出来,也是类似逻辑:

转载请注明:在路上 » 【已解决】html中返回上一页时保存之前的数据