[英]Adding to local storage only working after refreshing the page after button navigation to another page
I am developing an app that allows user to search for fishing lakes in their area. 我正在开发一个应用程序,允许用户搜索所在区域的钓鱼湖。 To do this they can type in their location which then displays fisheries near them that i have identified in the Json data.
为此,他们可以输入他们的位置,然后显示我在Json数据中标识的附近的渔业。 The search works perfectly with the code below i have written (i know it maybe a little flaky as i am not the best programmer).
该搜索可以与下面我编写的代码完美配合(由于我不是最好的程序员,所以我可能会觉得有点奇怪)。
//search
$(document).ready(function(){
$('#exampleSearch').keyup(function() {
var searchVal = $('#exampleSearch').val();
$('#results').empty();
console.log(searchVal);
var results = [];
$.getJSON("/data/locations.json",function(locations) {
for (var i = 0; i < locations.length; i++) {
if (locations[i].location.match(searchVal)) {
results.push(locations[i]);
}
}
$.each(results, function(index,result) {
var $resultsLi = $(
'<div class="row">'+
'<div class="twelve columns profile-information ">'+
'<div class="profile-title">'+
'<h6>'+result.name+'</h6>'+
'</div> ' +
' <img class= "favourites-pic" src="'+ result.image +'" alt="Fishery">'+
'<a class="view" href="'+ result.url + '" >View</a>'+
'</div>'+
' </div>'
)
$("#results").append($resultsLi);
});
});
});
});
I have now added a feature where users can now add their search results to their favourites page, by click a Add to favorites button on the page of the fishery they found from their search with the following code: 我现在添加了一项功能,用户现在可以通过使用以下代码单击从搜索中找到的渔业页面上的添加到收藏夹按钮,将搜索结果添加到收藏夹页面:
Javascript: 使用Javascript:
//Add to Favourites
$(function() {
$( ".addFavourites" ).on("click", function() {
try {
$(this).attr('disabled', true);
var locIdToAdd = $(this).closest("p").attr("id");
var myFavouriteLoc=JSON.parse(localStorage.getItem("favLoc"));
if (myFavouriteLoc == null) {
myFavouriteLoc = [];
}
if (myFavouriteLoc != null) {
for ( var j = 0; j < myFavouriteLoc.length; j++) {
if ( locIdToAdd == myFavouriteLoc[j]) {
alert("This property is already in your favourites");
myFavouriteLoc = [];
}
}
}
myFavouriteLoc.push(locIdToAdd);
localStorage.setItem("favLoc", JSON.stringify(myFavouriteLoc));
} catch (e) {
if (e == QUOTA_EXCEEDED_ERR) {
console.log("Error: Local storage limit exceeds");
} else {
console.log("ERROR: Saving to local storge.");
}
}
});
});
Html: HTML:
<p id="loc 1">
<input class="button-primary green addFavourites" type="submit" value="Add to Favourites">
</p>
THE PROBLEM 问题
Upon clicking the 'view' button on the search page results, and navigating to a fishery page. 单击搜索页面结果上的“查看”按钮后,导航至渔业页面。 I have a problem where i have to then refresh the page again before the add to favourites button will add anything to the local storage, it is clickable, but nothing happens.
我有一个问题,在添加到收藏夹按钮将任何内容添加到本地存储之前,我必须再次刷新页面,这是可单击的,但是没有任何反应。 once i refresh the page it works fine.
一旦我刷新页面,它就可以正常工作。
Can anyone help with why i have to refresh the page first? 谁能帮助我为什么必须首先刷新页面? any help is a appreciated :)
任何帮助是感激的:)
Try this jquery code to add favorites, it should work on each click: 尝试使用以下jquery代码添加收藏夹,它应在每次点击时起作用:
$( document ).on("click", ".addFavourites", function(e) {
e.preventDefault();
try {
$(this).attr('disabled', true);
var locIdToAdd = $(this).closest("p").attr("id");
var myFavouriteLoc=JSON.parse(localStorage.getItem("favLoc"));
if (myFavouriteLoc == null) {
myFavouriteLoc = [];
}
if (myFavouriteLoc != null) {
for ( var j = 0; j < myFavouriteLoc.length; j++) {
if ( locIdToAdd == myFavouriteLoc[j]) {
alert("This property is already in your favourites");
myFavouriteLoc = [];
}
}
}
myFavouriteLoc.push(locIdToAdd);
localStorage.setItem("favLoc", JSON.stringify(myFavouriteLoc));
} catch (e) {
if (e == QUOTA_EXCEEDED_ERR) {
console.log("Error: Local storage limit exceeds");
} else {
console.log("ERROR: Saving to local storge.");
}
}
});
Just make sure you are not putting this jquery function inside $(document).ready(function(){})
or $(function(){})
because it is not required 只要确保您没有将此jquery函数放入
$(document).ready(function(){})
或$(function(){})
因为它不是必需的
I can't see any code relating to loading the list of favourites, but I think it's fair to assume to that when the page loads you're loading the items from storage and placing them in, and then the pages where you add favourites and view favourites don't involve any loading between them. 我看不到任何与加载收藏夹列表有关的代码,但是我认为可以假设,当页面加载时,您正在从存储中加载项目并将其放入,然后在其中添加了收藏夹和查看收藏夹之间没有任何负载。 Therefore, of course, loading the items for the favourites list will only be performed on load, and so placing new items into the
localStorage
without reloading will not add them. 因此,当然,仅在加载时才加载收藏夹列表中的项目,因此无需重新加载就将新项目放置到
localStorage
不会添加它们。 So I'm going to cover a few things. 因此,我将介绍一些内容。
Firstly, don't use ==
and !=
. 首先,不要使用
==
和!=
。 They perform type coercion, (numbers to strings, strings to numbers, null
to undefined
, etc.), the rules for which are unintuitive and unmemorable and are best simply avoided, lest they cause difficult to diagnose problems in your code. 它们执行类型强制(从数字到字符串,从字符串到数字,从
null
到undefined
等),其规则不直观且难以记忆,最好避免使用,以免它们导致难以诊断代码中的问题。 Use ===
and !==
instead, these behave just like ==
and !=
does in other languages. 使用
===
和!==
代替,它们的行为就像==
和!=
在其他语言中一样。 If you want to perform type coercion I'd do so explicitly (eg Number('5')
). 如果您想执行类型强制,我会明确地执行(例如
Number('5')
)。
Secondly, and just as a suggestion, if you implement the local storage as an object, you won't need to loop and can simply use property names. 其次,作为一个建议,如果您将本地存储实现为对象,则无需循环,而只需使用属性名称即可。 So you can replace
所以你可以更换
if (myFavouriteLoc != null) {
for ( var j = 0; j < myFavouriteLoc.length; j++) {
if ( locIdToAdd == myFavouriteLoc[j]) {
With simply 与简单
if (myFavouriteLoc && myFavouriteLoc[locIdToAdd]) {
// ...
}
The object && object.property
idiom will perform a truthy check on both the object and the property, only passing if they are both truthy (not falsy). object && object.property
惯用语将对对象和属性均执行真实检查,只有在它们均为真实(不是虚假)的情况下才通过。 Here's a list of falsy values . 这是一个虚假的值列表 。
So, to answer your actual question. 因此,回答您的实际问题。 I'd say you have two options:
我说您有两种选择:
Going with my assumption in the first paragraph, I'd say that the second option is your best bet, as the constant page refreshes would provide a bad user experience. 按照我在第一段中的假设,我会说第二个选择是最好的选择,因为不断刷新页面会带来糟糕的用户体验。
So here's the jsfiddle 这是jsfiddle
(function bindBtns() {
$('.Table-btn--add').click(function () {
addBinding($(this));
});
$('.Table-btn--remove').click(function () {
removeBinding($(this));
});
})();
Here is an immediately invoked function, meaning it's run straight away. 这是一个立即调用的函数,这意味着它可以立即运行。 This will bind the existing buttons' behaviour, depending on whether they are add or remove buttons.
这将绑定现有按钮的行为,具体取决于它们是添加还是删除按钮。
function addBinding($btn) {
$btn.parent()
.detach()
.appendTo($('#favourites'));
// add to local storage here
modifyAttributes($btn);
}
Here's the behaviour for the binding, fairly straight forward, but: 这是绑定的行为,相当简单,但是:
Place your behaviour for adding or removing from local storage where I've placed the comments. 将您的行为用于添加或从我放置评论的本地存储中删除。
removeBinding
is exactly the same except it appends to the other table. removeBinding
完全相同,只是它附加到另一个表上。
function modifyAttributes($btn) {
if ($btn.hasClass('Table-btn--add')) {
$btn.text('Remove')
.removeClass('Table-btn--add')
.addClass('Table-btn--remove')
.off('click')
.click(removeBinding.bind(null, $btn));
} else if ($btn.hasClass('Table-btn--remove')) {
$btn.text('Add')
.removeClass('Table-btn--remove')
.addClass('Table-btn--add')
.off('click')
.click(addBinding.bind(null, $btn));
}
}
.bind
here .bind
信息 In your version you would replace .Table-btn--add
with .addFavourites
, and place addBinding($(this))
in your try block, and then you can just copy over the other functiona verbatim (I think). 在您的版本中,您将
.Table-btn--add
.addFavourites
用.addFavourites
,并将addBinding($(this))
放在try块中,然后您可以逐字复制其他函数(我认为)。
Good luck! 祝好运! Sorry that got so long, and let me know how it goes.
抱歉,时间太长了,让我知道如何进行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.