本文介绍了如何在jQuery中存储全局值(不一定是全局变量)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前我正在使用大量JavaScript,jQuery,Microsoft客户端JavaScript和其他库的旧版网页上工作。底线 - 我无法从头开始重写整个页面,因为业务无法证明它的正确性。所以...它就是这样。无论如何,我需要用变量来污染(我真的没有试过)全局命名空间。有三种选择我正在考虑 -


  1. 使用正常的JavaScript声明来存储/检索它 - var x = 0;

    使用jQuery存储/检索DOM标记中的值 - $(body)。data(x,0);


  2. 使用隐藏表单字段, /使用jQuery检索值 - $(whatever)。data(x,0);

  3. ol>

    有没有更好的方法?我查看了现有的一堆代码,并且我不相信该变量可以在函数中作用域。 在jQuery对象中创建一个名称空间,如下所示:

      $。mynamespace = {
    myVar:something,
    myVar2:somethingElse
    };

    或:

      $。mynamespace = {}; 
    $ .mynamespace.myVar =something;
    $ .mynamespace.myVar2 =somethingElse;请记住,任何名为'mynamespace'的插件方法都会被覆盖,因此请务必使用一个合理的名称。


    Currently I am working on a legacy web page that uses a ton of JavaScript, jQuery, Microsoft client JavaScript, and other libraries. The bottom line - I cannot rewrite the entire page from scratch as the business cannot justify it. So... it is what it is. Anyway, I need to pollute (I really tried not too) the global namespace with a variable. There are the three options I was thinking about -

    1. Just store/retrieve it using a normal JavaScript declaration - var x = 0;

    2. Use jQuery to store/retrieve the value in a DOM tag - $("body").data("x", 0);

    3. Use a hidden form field, and set/retrieve the value with jQuery - $("whatever").data("x", 0);

    Is there a better way? I looked at the existing pile of code, and I do not believe the variable can be scoped in a function.

    解决方案

    You can create a namespace inside the jQuery object, like so:

    $.mynamespace = { 
        myVar : "something", 
        myVar2 : "somethingElse" 
    }; 
    

    or:

    $.mynamespace = {};
    $.mynamespace.myVar = "something";
    $.mynamespace.myVar2 = "somethingElse";
    

    Bear in mind, any plugin method named 'mynamespace' will be overwritten so be sure to use a sensible name.

    这篇关于如何在jQuery中存储全局值(不一定是全局变量)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-21 07:45