简体   繁体   English

仅在按钮导航到另一页后刷新页面后,才能添加到本地存储

[英]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. 它们执行类型强制(从数字到字符串,从字符串到数字,从nullundefined等),其规则不直观且难以记忆,最好避免使用,以免它们导致难以诊断代码中的问题。 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: 我说您有两种选择:

  1. Reload the page on each addition, or 在每次添加时重新加载页面,或者
  2. AJAXily add the entry to your views when favourites are added. 添加收藏夹后,AJAXily将条目添加到您的视图中。 Favourites will then, of course, need be removed 然后,当然需要删除收藏夹

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: 这是绑定的行为,相当简单,但是:

  1. Select the buttons parent, ie the row 选择按钮parent,即行
  2. Detach it from the DOM, ie the current table 从DOM(即当前表)中分离它
  3. Attach it to the other table 将其附加到另一个表
  4. Rebind the button to perform the opposite behaviour, shown below 重新绑定按钮以执行相反的行为,如下所示

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));
    }
}
  1. Split on whether this is an adding button, or a removing button. 对这是添加按钮还是删除按钮进行拆分。 (The next steps will be for both versions.) (接下来的步骤将同时适用于两个版本。)
  2. Update the text to be the opposite, (add -> remove, remove -> add) 更新文本为相反,(添加->删除,删除->添加)
  3. Remove the current class 删除当前课程
  4. Add the new class 添加新课程
  5. Remove the old click binding 删除旧的单击绑定
  6. Bind the new click binding. 绑定新的单击绑定。 Read about .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.

相关问题 本地存储只有在刷新页面后才会更新,有没有办法在 setItem 调用后立即更新它 - Local storage is getting updated only after refreshing the page, is there any way to update it immediately after the setItem call 推送器仅在刷新页面后工作 - Pusher working only after refreshing page 单击按钮后如何在不刷新页面的情况下显示本地存储的内容? - How do I display the contents of local Storage after button click without refreshing the page? 使用本地存储刷新页面后如何保存用户输入 - How to save user inputs after refreshing the page using local storage 后退按钮后刷新页面 - Refreshing page after back button 导航到新页面后无法读取本地存储 - Can't read local storage after navigation to a new page 刷新页面后过滤器不起作用 - Filter not working after refreshing the page 仅在刷新页面后,按注销按钮后导航栏不更新 - Navbar not updating upon pressing the logout button, only after refreshing the page 为什么刷新页面后我在页面上的输入消失了,但是输入保存在控制台的本地存储中? - Why do my inputs on the page disappear after refreshing the page, but the inputs are saved in local storage in the console? JavaScript仅在刷新页面多次后才能工作 - JavaScript only working after Refreshing Page multiple times
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM