从函数返回更新变量

Return updating variable from function

本文关键字:变量 更新 返回 函数      更新时间:2023-09-26

我正在尝试使用 javascript/jQuery 来查找窗口的宽度并在后面的函数中使用该变量。

$(function resizer() {
    function doneResizing() {
        var windowWidth = $(window).width();
        return windowWidth;
    }
    var getWidth = doneResizing();

    var id;
    $(window).resize(function() {
        clearTimeout(id);
        id = setTimeout(doneResizing, 0);
    });
    doneResizing();

    return getWidth;
});
var finalWidth = resizer()

因此,每当调整窗口大小并自动更新windowWidth时,调整大小函数就会更新。当变量在函数外部返回时,除非我刷新页面,否则getWidth不会通过窗口大小调整进行更新。有什么想法吗?我 2 周前刚刚拿起 js/jq,我正在尽最大努力解决退货和关闭问题,所以我可能忽略了这里的一些东西。谢谢。

执行以下操作

要简单得多:

var finalWidth;
$( document ).ready(function() {
      //Set this the first time
      finalWidth = $(window).width();       
      $(window).resize(function() {
      //resize just happened, pixels changed
       finalWidth = $(window).width();
        alert(finalWidth); //and whatever else you want to do
        anotherFunction(finalWidth); 
    });
 });

并在外部使用最终宽度,因为它是全局变量。您可以获得相同的功能,而不会变得复杂。

更新

正如评论的那样,全局变量是不好的实践(例如,也是 http://dev.opera.com/articles/view/javascript-best-practices/)。

为了避免全局变量finalWidth可以在document.ready内部移动,并且可以从事件处理程序内部调用任何必要的函数resize(function() {

更新 2

由于拖动导致多个调整大小事件的问题,代码已更新。

参考:JQuery:如何在完成调整大小后调用调整大小事件?

JSFiddle: http://jsfiddle.net/8ATyz/1/

$( document ).ready(function() {
      var resizeTimeout;
      $(window).resize(function() {
        clearTimeout(resizeTimeout);
        resizeTimeout= setTimeout(doneResizing, 500);      
     });
      doneResizing(); //trigger resize handling code for initialization 
 });

function doneResizing()
{
    //resize just happened, pixels changed
    finalWidth = $(window).width();
    alert(finalWidth); //and whatever else you want to do
    anotherFunction(finalWidth);    
}
function anotherFunction(finalWidth)
{
    alert("This is anotherFunction:"+finalWidth);   
}

你把resizer函数和jQuery ready函数混为一谈了。要跟踪窗口宽度,您可以这样做

(function ($) {
    var windowWidth;
    // when the document is fully loaded
    $(function(){
        // add an resize-event listener to the window
        $(window).resize(function(){
            // that updates the variable windowWidth
            windowWidth = $(window).width();
        })
        // trigger a resize to initialize windowWidth
        .trigger('resize');
        // use windowWidth here.
        // will be updated on window resize.
    });
}(jQuery));