每次调整窗口大小时,如何更新另一个函数中的变量?
代码如下:
$(window).resize(function() {
Here is the NewVarialble;
});
(function (a) {
OldVariable;
Want to update the OldVarible with NewVariable;
})(jQuery);
答案 0 :(得分:0)
var resizeMe = function (newVar) {
var oldVar = newVar;
}
$(window).resize(function (r) {
console.log(r);
var newV = r;
resizeMe(newV);
});
答案 1 :(得分:0)
这并不是100%清楚你遇到了什么问题,但似乎只是关于范围。
这可能对范围等有用 http://javascript.crockford.com/code.html
这里有一个工作版本 - 在js中使用下面粘贴的代码,我不建议在窗口对象上使用变量,它仅用于演示
$(document).ready(function(){// wrapper function / scope change as appropriate
window.OldVariable = -1; // placed globally but change as appropriate
$(window).resize(function() {
var NewVariable; // null initially
NewVariable = Math.random();// assign a random number
updateOldVar(NewVariable);
});
function updateOldVar(a) {
window.OldVariable = a;
//console.log(window.OldVariable);
}
$('.testbtn').on('click', function() {
console.log(window.OldVariable);
});
});
继续下面的评论 修改强>
$(document).ready(function () {// wrapper function / scope change as appropriate
var d = {
divalayerWidth: 0,
divalayerHeight: 0
};
$(window).resize(onWindowResize);
function onWindowResize(e){
updateD(d, e.target.outerWidth, e.target.outerHeight);
}
function updateD(d, w, h){
d.divalayerWidth = w;
d.divalayerHeight = h;
}
});
答案 2 :(得分:0)
将变量设为全局变量(坏主意)或将调整大小块移动到自执行匿名函数中,如下所示:
(function (a) {
OldVariable;
$(window).resize(function() {
this now has access to oldvariable
});
})(jQuery);