【问题标题】:Variable not passing into function?变量没有传递给函数?
【发布时间】:2013-08-12 11:17:55
【问题描述】:

我试图用谷歌搜索,但找不到解决方案。所以问题是,如果用户窗口宽度更改为特定宽度+-,我会尝试执行一次;由于某种原因,该变量在函数内部未定义

代码如下:

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,则执行一些操作。

提前致谢。

【问题讨论】:

标签: javascript jquery variables if-statement


【解决方案1】:

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

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

那么你只需要在你设置tc的值的每个位置删除var

【讨论】:

  • 没问题,很乐意提供帮助。
【解决方案2】:

我看到了几件事。

你总是重新声明变量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,它总是会进入第一个条件...

我相信您可能想使用'&lt;''&gt;'

【讨论】:

    猜你喜欢
    • 2021-04-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-28
    • 1970-01-01
    • 2012-03-02
    相关资源
    最近更新 更多