比Window.Object更好的方法?

时间:2014-07-15 10:03:32

标签: jquery object global-variables

jquery有更好的方法来存储全局变量吗?

window.activedepth = 0;

$(document).ready(function() {
alert(window.activedepth);
//other functions that use activedepth
})
我很好奇。我需要存储激活的菜单深度。 http://jsfiddle.net/dichterDichter/dX34n/2/embedded/result/

修改 现在,如果没有全球Vars,那么效果很好,那就是:adeneo http://jsfiddle.net/dichterDichter/R3tsp/

3 个答案:

答案 0 :(得分:1)

在函数外部,变量声明是全局的。所以,

var activedepth = 0; //global variable

$(document).ready(function() {
alert(activedepth);
//other functions that use activedepth
})

和你一样。

答案 1 :(得分:1)

有可能避免"全局变量"完全,只需在使用所述变量的所有函数的范围内使用词法变量:

$(document).ready(function() {
    var activedepth;
    // Other functions and usage of said variable here here..
})

但是,这并不适用于<script>元素或内联事件处理程序。

答案 2 :(得分:1)

是的。 jQuery有一个内部$.data对象,您可以在其中存储数据,这样您就可以在不需要全局变量的情况下基于每个元素存储数据。

$(document).ready(function() {

    $(window).data('activeDepth', 0);

});

jQuery.data( document.body, 'activeDepth', 0 );

jQuery.data

$(element).data()

相关问题