gpt4 book ai didi

javascript - 变量没有传递给函数?

转载 作者:行者123 更新时间:2023-11-29 17:15:47 24 4
gpt4 key购买 nike

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

代码如下:

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

提前致谢。

最佳答案

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

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

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

关于javascript - 变量没有传递给函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18185623/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com