我想在 JavaScript 代码中保存用户首选项

发布于 2024-11-29 10:13:41 字数 1327 浏览 0 评论 0原文

我有这段 javascript 代码可以改变网站的风格。但此代码仅在您单击它时更改样式。刷新页面后,它会恢复默认状态。我希望它保存用户的偏好。我真的很喜欢这段代码,我不想用另一段代码来改变它。你能帮忙吗?

<script type="text/javascript">
    $(document).ready(function() {
        $("#fullswitch").click(function() {
            $("#chpheader").removeClass("compact");
               $("#imgg").removeClass("compact");
               $("#chpheader").removeClass("original");
            $("#imgg").removeClass("original");
                            $("#chpheader").addClass("normal");
            $("#imgg").addClass("normal");

        });
        $("#compactswitch").click(function() {
            $("#chpheader").addClass("compact");
            $("#imgg").addClass("compact");
            $("#chpheader").removeClass("original");
            $("#imgg").removeClass("original");
            $("#chpheader").removeClass("normal");
            $("#imgg").removeClass("normal");

        });
          $("#originalswitch").click(function() {
            $("#chpheader").addClass("original");
            $("#imgg").addClass("original");
            $("#chpheader").removeClass("compact");
               $("#imgg").removeClass("compact");
                            $("#chpheader").removeClass("normal");
            $("#imgg").removeClass("normal");

        });

    });
</script>

I have this javascript code that changes the style of the website. but this code changes the style only when you click on it. and after you refresh the page it returns to default. I want it to save the users prefrences. I really like the code and I do not want to change it with another one. can you please help.

<script type="text/javascript">
    $(document).ready(function() {
        $("#fullswitch").click(function() {
            $("#chpheader").removeClass("compact");
               $("#imgg").removeClass("compact");
               $("#chpheader").removeClass("original");
            $("#imgg").removeClass("original");
                            $("#chpheader").addClass("normal");
            $("#imgg").addClass("normal");

        });
        $("#compactswitch").click(function() {
            $("#chpheader").addClass("compact");
            $("#imgg").addClass("compact");
            $("#chpheader").removeClass("original");
            $("#imgg").removeClass("original");
            $("#chpheader").removeClass("normal");
            $("#imgg").removeClass("normal");

        });
          $("#originalswitch").click(function() {
            $("#chpheader").addClass("original");
            $("#imgg").addClass("original");
            $("#chpheader").removeClass("compact");
               $("#imgg").removeClass("compact");
                            $("#chpheader").removeClass("normal");
            $("#imgg").removeClass("normal");

        });

    });
</script>

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

_蜘蛛 2024-12-06 10:13:41
<html>
<body>
 <span id="t1">0</span> 
 <span id="t2">0</span>
 <span id="t3">0</span> 
 <span id="t4">0</span>
 <span id="t5">0</span>
 <span id="t6">0</span> 
<div id="result"></div>

<script>
// Check browser support
if (typeof(Storage) !== "undefined") {
  // Store
  localStorage.setItem("lastname", "Smith");
   localStorage.setItem("first", "Smi");
  // Retrieve
  var c = document.getElementById("result").innerHTML = localStorage.getItem("lastname");
 var b = document.getElementById("result").innerHTML = localStorage.getItem("first");
document.getElementById("t1").innerHTML = c;
document.getElementById("t2").innerHTML = b;
//localStorage.removeItem("lastname");

} else {
  document.getElementById("result").innerHTML = "Sorry, your browser does not support Web Storage....";
}
</script>

</body>
</html>
<html>
<body>
 <span id="t1">0</span> 
 <span id="t2">0</span>
 <span id="t3">0</span> 
 <span id="t4">0</span>
 <span id="t5">0</span>
 <span id="t6">0</span> 
<div id="result"></div>

<script>
// Check browser support
if (typeof(Storage) !== "undefined") {
  // Store
  localStorage.setItem("lastname", "Smith");
   localStorage.setItem("first", "Smi");
  // Retrieve
  var c = document.getElementById("result").innerHTML = localStorage.getItem("lastname");
 var b = document.getElementById("result").innerHTML = localStorage.getItem("first");
document.getElementById("t1").innerHTML = c;
document.getElementById("t2").innerHTML = b;
//localStorage.removeItem("lastname");

} else {
  document.getElementById("result").innerHTML = "Sorry, your browser does not support Web Storage....";
}
</script>

</body>
</html>
伏妖词 2024-12-06 10:13:41

有一个 jQuery cookie 插件 该页面上也有示例,因此您可以了解如何设置并从 cookie 读取值。

读取该值后,只需加载正确的主题即可。

var theme = $.cookie('name_of_selected_theme');
setTheme(theme);

function setTheme(themeName){
   if(themeName == "One"){
     ...
   }else...
}

然而,cookie 只允许 4KB 的数据,并且会在每个 HTTP 调用中传递。更好的主意是本地存储。您可以使用 YUI Storage Lite 库,它是 YUI Storage Lite 库大小为 3KB,您可以轻松使用它在浏览器 localStorage 中保存数据并从中加载。使用 localStorage 可以保存至少 5MB 的数据。

上面链接中的示例代码:

YUI({
    //Last Gallery Build of this module
    gallery: 'gallery-2010.12.01-21-32'
}).use('gallery-storage-lite', function (Y) {

    // For full compatibility with IE 6-7 and Safari 3.x, you should listen for
    // the storage-lite:ready event before making storage calls. If you're not
    // targeting those browsers, you can safely ignore this step.
    Y.StorageLite.on('storage-lite:ready', function () {

        // To store an item, pass a key and a value (both strings) to setItem().
        Y.StorageLite.setItem('kittens', 'fluffy and cute');

        // If you set the optional third parameter to true, you can use any
        // serializable object as the value and it will automatically be stored
        // as a JSON string.
        Y.StorageLite.setItem('pies', ['apple', 'pumpkin', 'pecan'], true);

        // To retrieve an item, pass the key to getItem().
        Y.StorageLite.getItem('kittens');    // => 'fluffy and cute'

        // To retrieve and automatically parse a JSON value, set the optional
        // second parameter to true.
        Y.StorageLite.getItem('pies', true); // => ['apple', 'pumpkin', 'pecan']

        // The length() method returns a count of how many items are currently
        // stored.
        Y.StorageLite.length(); // => 2

        // To remove a single item, pass its key to removeItem().
        Y.StorageLite.removeItem('kittens');

        // To remove all items in storage, call clear().
        Y.StorageLite.clear();

    });

});

There is a jQuery cookie plugin there are examples on that page as well so you can see how you can set and read a value from the cookie.

Once the value is read it's just a simple matter of loading the right theme.

var theme = $.cookie('name_of_selected_theme');
setTheme(theme);

function setTheme(themeName){
   if(themeName == "One"){
     ...
   }else...
}

However cookies only allow for 4KB of data and are passed in every HTTP call. A better idea many be localStorage. You can use YUI Storage Lite library which is < 3KB in size and you can easily use it to save data in browser localStorage and load from it. You can save at least 5MB of data using localStorage.

Example code from the link above:

YUI({
    //Last Gallery Build of this module
    gallery: 'gallery-2010.12.01-21-32'
}).use('gallery-storage-lite', function (Y) {

    // For full compatibility with IE 6-7 and Safari 3.x, you should listen for
    // the storage-lite:ready event before making storage calls. If you're not
    // targeting those browsers, you can safely ignore this step.
    Y.StorageLite.on('storage-lite:ready', function () {

        // To store an item, pass a key and a value (both strings) to setItem().
        Y.StorageLite.setItem('kittens', 'fluffy and cute');

        // If you set the optional third parameter to true, you can use any
        // serializable object as the value and it will automatically be stored
        // as a JSON string.
        Y.StorageLite.setItem('pies', ['apple', 'pumpkin', 'pecan'], true);

        // To retrieve an item, pass the key to getItem().
        Y.StorageLite.getItem('kittens');    // => 'fluffy and cute'

        // To retrieve and automatically parse a JSON value, set the optional
        // second parameter to true.
        Y.StorageLite.getItem('pies', true); // => ['apple', 'pumpkin', 'pecan']

        // The length() method returns a count of how many items are currently
        // stored.
        Y.StorageLite.length(); // => 2

        // To remove a single item, pass its key to removeItem().
        Y.StorageLite.removeItem('kittens');

        // To remove all items in storage, call clear().
        Y.StorageLite.clear();

    });

});
同尘 2024-12-06 10:13:41

我想你有两个选择,存储信息客户端,或存储信息服务器端。

如果您实际上有一个“用户”服务器端(该人必须登录,yada yada yada),您可以为用户存储此设置(将一些数据添加到存储用户信息的位置)。

如果您不希望它那么持久,您可以将其存储在本地存储(对浏览器不太友好)或 cookie 中。您确实无法保证这些设置会保留下来,因为它们是由浏览器控制的,用户可以将其浏览器设置为从不保存此信息。

无论哪种方式(客户端或服务器),您都可以读取设置并在服务器端设置类,并跳过用于更改类的 javascript。在服务器上进行总是更好。

I suppose you have two options, store the info client side, or store the info server side.

If you actually have a "user" server side (the person has to log in, yada yada yada), you can store this setting for the user (add some data to where ever the user info is stored).

If you don't want it that persistent, you can store it in local storage (not very browser friendly) or cookies. You really have no guarantee that these settings will stay around, as they are controlled by the browser, users can have their browsers set to never save this info.

Either way (client or server) you can read the setting and set the classes server-side and skip the javascript for changing the classes. Always better to do it on the server.

我的鱼塘能养鲲 2024-12-06 10:13:41

您可以使用 HTML5 window.localStorage 来存储用户首选项并触发相应的布局更改。

或者按照之前的建议使用 cookie。

看看这篇文章:http://diveintohtml5.ep.io/storage.html

You may use HTML5 window.localStorage to store user preferences and trigger the corresponding layout changes.

Or use cookies as previously suggested.

Take a look at this article: http://diveintohtml5.ep.io/storage.html

乄_柒ぐ汐 2024-12-06 10:13:41

使用 cookie 来存储用户选项。

http://www.quirksmode.org/js/cookies.html

Use cookies to store the users options.

http://www.quirksmode.org/js/cookies.html

一笑百媚生 2024-12-06 10:13:41

使用 localStorage 存储用户首选项,并在重新加载时重新加载首选项。

这是一个很好的选择教程。

怎么写:
localStorage['someKey'] = 5;
如何阅读:var lastKeyValue = localStorage['someKey'];

Use localStorage to store the user preferences, and on reload load the preferences back in.

Here's a good tutorial.

How to write:
localStorage['someKey'] = 5;
How to read: var lastKeyValue = localStorage['someKey'];

醉酒的小男人 2024-12-06 10:13:41

使用会话存储

   //set in session storage
    $("#block-menu-menu-organisation > ul > li > a" ).bind( "click", function(evt) {
      //in that case one expanded at the time
      sessionStorage.clear();
       var par = $(evt.target).parent();
       sessionStorage.setItem(par.attr('id'),par.attr('class'));    
       console.log(par.attr('class'));         
    });


 //    //retrieve class from session
if(typeof sessionStorage!='undefined') {
    $('#block-menu-menu-organisation > ul > li' ).each(function(i)  {           
        if( $(this).attr('id') in sessionStorage) {     
            $(this).attr('class', sessionStorage.getItem($(this).attr('id')));          
        }
        });
}

use session storage

   //set in session storage
    $("#block-menu-menu-organisation > ul > li > a" ).bind( "click", function(evt) {
      //in that case one expanded at the time
      sessionStorage.clear();
       var par = $(evt.target).parent();
       sessionStorage.setItem(par.attr('id'),par.attr('class'));    
       console.log(par.attr('class'));         
    });


 //    //retrieve class from session
if(typeof sessionStorage!='undefined') {
    $('#block-menu-menu-organisation > ul > li' ).each(function(i)  {           
        if( $(this).attr('id') in sessionStorage) {     
            $(this).attr('class', sessionStorage.getItem($(this).attr('id')));          
        }
        });
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文