【问题标题】:How to run namespaced function onclick and on windows.resize如何在 onclick 和 windows.resize 上运行命名空间函数
【发布时间】:2018-09-14 03:01:46
【问题描述】:

我有这个功能,可以在单击页眉时折叠/展开页脚中的项目。它按预期工作。但是,我需要给函数命名空间,但我不能让它工作。

现有功能:

var footerHeader = jQuery('.footer-heading');
var footerColumn = jQuery('.footer-heading + .footerlinks');
var cachedWidth = jQuery('body').prop('clientWidth');

var collapseFooter = function(el, ev) {
  // Collapse footer at specified break point
  if (window.matchMedia('(max-width: 991px)').matches) {
    ev.preventDefault();
    jQuery(el).next('ul').slideToggle();
    jQuery(el).toggleClass('open');
  } else {
    jQuery(el).next('ul').show();
  }
};

footerHeader.click(function(e) {
  collapseFooter(this, e);
});

//On resize, wait and remove redundant footer styling
var it;
window.onresize = function() {
  clearTimeout(it);
  it = setTimeout(function() {
    var newWidth = jQuery('body').prop('clientWidth');
    if (newWidth !== cachedWidth) {
      footerHeader.removeClass('open');
      footerColumn.removeAttr('style');
      cachedWidth = newWidth;
    }
  }, 200);
};

这是我目前制作的命名空间版本:

var globalFooter = {
  footerColumn: jQuery('.footer-heading + .footerlinks'),
  cachedWidth: jQuery('body').prop('clientWidth'),

  collapseFooter: function (el, ev) {
    if (window.matchMedia('(max-width: 991px)').matches) {
      ev.preventDefault();
      jQuery(el).next('ul').slideToggle();
      jQuery(el).toggleClass('open');
    } else {
      jQuery(el).next('ul').show();
    }
  }
}
jQuery('.footer-heading').on('click', globalFooter.collapseFooter(this, ev));

我无法让它工作:"Uncaught ReferenceError: ev is not defined"。如果我删除"ev",它仍然无法工作。

HTML:

<h3 class="footer-heading">Heading</h3>
<ul class="footerlinks" role="menu">
  <li role="menuitem"><a href="#">One</a></li>
  <li role="menuitem"><a href="#">Two</a></li>
  <li role="menuitem"><a href="#">Three</a></li>
  <li role="menuitem"><a href="#">Four</a></li>
</ul>

JsFiddle here.

【问题讨论】:

    标签: jquery namespaces


    【解决方案1】:

    当您为函数提供参数时,您需要将其包装在另一个匿名函数中:

    jQuery('.footer-heading').on('click', function(e) {
      globalFooter.collapseFooter(this, e);
    });
    

    【讨论】:

      猜你喜欢
      • 2017-11-27
      • 2011-12-04
      • 1970-01-01
      • 1970-01-01
      • 2011-11-07
      • 1970-01-01
      • 1970-01-01
      • 2016-03-20
      • 2021-12-06
      相关资源
      最近更新 更多