变量不传入函数?

时间:2013-08-12 11:17:55

标签: javascript jquery variables if-statement

我试图谷歌这个但找不到解决方案。所以问题是如果用户窗口宽度改变为特定宽度+,我试图执行一次,但是;由于某种原因,函数内部的变量是 undefined

以下是代码:

jQuery(document).ready(function ($) {

var windowWidth = $(window).width();
var n = 1;

if(windowWidth >= 900) { 
    var tc = 3; 
    $(".debug").html(tc); // Making sure if user window width is 900 or more and tc is 3 on page load.
} else if (windowWidth <= 900) {
    var tc = 2;
    $(".debug").html(tc); // Making sure if user window width is 900 or less and tc is 2 on page load.
}

function liveWidthChange(){
    var windowWidth = $(window).width();
    $(".debug2").html("<b>current width:</b> " + windowWidth + " - <b>tc:</b> " + tc); 
    if (tc == 3 && windowWidth <= 900) {
         // Shows how many times executed if activly changing browser width and the current value of tc
        $(".debug").html("tc Value: " + tc);
        var tc = 2;
    }
}

// If the browser changes size
var RS = false;
$(window).resize(function() { 
    if (RS !== false) clearTimeout(RS);
    RS = setTimeout(liveWidthChange, 200);
});    

});

因此,如果用户的窗口宽度为900或更高,则将tc变量设置为3,如果用户正在调整浏览器大小并且它低于900,则执行某些操作。

提前致谢。

2 个答案:

答案 0 :(得分:4)

您需要在所有功能都可以访问它的地方声明tc

var windowWidth = $(window).width();
var n = 1;
var tc; // here, at the top.

然后,您只需删除设置var值的每个位置的tc

答案 1 :(得分:1)

我看到了几件事。

您始终重新声明变量tc,而应将其移到顶部

$(document).ready(function ($) {
  var originalWidth = $(window).width();
  var n = 1;
  var tc = 2;
  var MAX_WIDTH = 900;
  [...]

您会因为使用相同名称命名两个不同的变量而感到困惑:

在就绪区块中:

var originalWidth = $(window).width();

在功能中:

var currentWidth = $(window).width();

您正在使用运算符'=='来比较整数,除非您知道自己在做什么,否则应使用'==='

x = "5"
>>> x == 5
true
>>> x === 5
false

在你的情况下你有

if(windowWidth >= 900) {}  else if (windowWidth <= 900) {}

如果windowWidth = 900,它将始终进入第一个条件......

我相信您可能想要使用'<''>'

相关问题