是否有更好的方法为jquery存储全局变量?
window.activedepth = 0;
$(document).ready(function() {
alert(window.activedepth);
//other functions that use activedepth
})
我只是好奇。我需要存储激活菜单的深度。http://jsfiddle.net/dichterDichter/dX34n/2/embedded/result/
编辑:在没有全局变量的情况下工作得很好,这要归功于:adeneohttp://jsfiddle.net/dichterDichter/R3tsp/
有。jQuery有一个可以存储数据的内部$.data
对象,这样你就可以在每个元素的基础上存储数据,而不需要全局变量。
$(document).ready(function() {
$(window).data('activeDepth', 0);
});
或
jQuery.data( document.body, 'activeDepth', 0 );
jQuery.data
$(元素). data ()
函数外部的变量声明是全局的。
var activedepth = 0; //global variable
$(document).ready(function() {
alert(activedepth);
//other functions that use activedepth
})
完全避免使用"全局变量"是可能的,只需在所有使用该变量的函数的作用域内使用一个词法变量:
$(document).ready(function() {
var activedepth;
// Other functions and usage of said variable here here..
})
这并不适用于<script>
元素或内联事件处理程序。