简体   繁体   English

javascript在页面重新加载后保留值

[英]javascript keep values after page reload

I have a general question. 我有一个一般性的问题。 I got a form made with django, if i use submit, but not all data is correct or when there are required fields missing, the page jumps back to default. 我得到了用django制作的表格,如果我使用Submit,但是并非所有数据都是正确的,或者当缺少必填字段时,页面会跳回默认值。 The values inside the form are saved but not the page lay-out. 表单中的值将被保存,但页面布局不会被保存。

my javascript that changes lay-out: 我的javascript更改布局:

$(function(){
    $('li.fields').slice(1).hide();

    $('ul').on('click', 'li.title', function(){
        $(this).next().slideToggle(200)
    })
});

short said, I would like to keep the status of the (un)collapsed fields. 简而言之,我想保留(未折叠)字段的状态。 Could someone please point me in the right direction to achieve that (new to javascript) 有人可以指出正确的方向来实现这一目标(javascript的新手)

If you can't use AJAX (or don't know how to use it), you can use a hidden field in your form. 如果您不能使用AJAX(或不知道如何使用它),则可以在表单中使用隐藏字段。

I've created a fiddle to simulate that . 我创建了一个小提琴来模拟

HTML: HTML:

<input type="hidden" id="myHiddenField" />

Updated Javascript: 更新的Javascript:

$(function(){
    $('li.fields').slice(1).hide();

    $('ul').on('click', 'li.title', function(){
        $(this).next().slideToggle(200);
        var myString = "[ "; // create a string to simulate an Array
        $('ul li.title').each(function() {
            myString += $(this).is(":visible").toString() + ", "; // iterate your list to take the visible values
        });
        myString += " ]"; // finishes the Array
        $("#myHiddenField").val(myString); // populate your hidden field
    })

    // when you get back from a submit, this hidden field will have some values
    if ($("#myHiddenField").val() != "") {
        var arr = eval($("#myHiddenField").val()); // turn the string into an Array
        for (var i = 0; i < arr.length; i++) { // iterate the Array
            if (!arr[i])
                $("ul li.title").eq(i).hide(); // if the Array item is false, hide the respective li
        }
    }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM