访问功能逻辑之外的变量

时间:2017-04-15 13:18:56

标签: jquery variables scope global

   $(window).on("load resize", function () {
      if ($(window).width() < 768) {
          menuHeight = '0px';
          contactHeight = '100%';
      } else {
          menuHeight = ($('#desktop-menu').height() + 'px').toString();
          contactHeight = ($('.get-in-touch-home').outerHeight() + 'px').toString();
      }
   });

我想在这个函数之外访问这两个变量(menuHeight,contactHeight)以便在别处使用。我正在测量一个模态的顶部高度,但是不要仅仅调整大小,而不仅仅是加载(在这种情况下似乎很简单的If / Else会起作用。)我可能需要在范围内进行一些学习。谢谢!

2 个答案:

答案 0 :(得分:2)

您可以在函数外部定义它们。此外,由于load在页面加载过程中发生得相当晚,因此您需要主动初始化它们,然后根据loadresize更新它们。这表明你想要一个可重复使用的功能:

var menuHeight;                            // Defining...
var contactHeight;                         // ...them
grabHeights();                             // Proactive
$(window).on("load resize", grabHeights);  // And on events

function grabHeights() {
    if ($(window).width() < 768) {
        menuHeight = '0px';
        contactHeight = '100%';
    }
    else {
        menuHeight = ($('#desktop-menu').height() + 'px').toString();
        contactHeight = ($('.get-in-touch-home').outerHeight() + 'px').toString();
    }
}

如果您的代码已经不在范围函数中,您可能希望将其合并为一个:

(function() {
    var menuHeight;
    var contactHeight;
    grabHeights();
    $(window).on("load resize", grabHeights);

    function grabHeights() {
        if ($(window).width() < 768) {
            menuHeight = '0px';
            contactHeight = '100%';
        }
        else {
            menuHeight = ($('#desktop-menu').height() + 'px').toString();
            contactHeight = ($('.get-in-touch-home').outerHeight() + 'px').toString();
        }
    }
})();

...因为全局变形是一件坏事。 : - )

您会看到有人告诉您继续挂机,然后手动触发:

$("selector").on("event", function() {
    // ...
}).triger("event");

我不是粉丝。如果你需要调用一个函数,只需调用它。

答案 1 :(得分:0)

您需要在之前定义它们:

var menuHeight = '';
var contactHeight = '';

$(window).on("load resize", function () {
    if ($(window).width() < 768) {
        menuHeight = '0px';
        contactHeight = '100%';
    } else {
        menuHeight = ($('#desktop-menu').height() + 'px').toString();
        contactHeight = ($('.get-in-touch-home').outerHeight() + 'px').toString();
    }
});

您可以使用以下功能:

function scroll() {
  var menuHeight;
  var contactHeight;

  if ($(window).width() < 768) {
    menuHeight = '0px';
    contactHeight = '100%';
  } else {
    menuHeight = ($('#desktop-menu').height() + 'px').toString();
    contactHeight = ($('.get-in-touch-home').outerHeight() + 'px').toString();
  }

  getHeight(menuHeight,contactHeight)

}

function getHeight(menuHeight,contactHeight) {
  console.log(menuHeight,contactHeight)
}

$(window).scroll(scroll);

全球访问(不推荐)

window.menuHeight = '';
window.contactHeight = '';