jquery - 如何在 onclick 和 windows.resize 上运行命名空间函数

标签 jquery namespaces

我有这个功能,可以在单击标题时折叠/展开页脚中的项目。它按预期工作。但是,我需要为该函数命名,但无法使其工作。

现有功能:

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"它仍然不起作用。

网址:
<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('.footer-heading').on('click', function(e) {
  globalFooter.collapseFooter(this, e);
});

关于jquery - 如何在 onclick 和 windows.resize 上运行命名空间函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49652882/

相关文章:

r - 在一个 .R 文件中定义所有函数,从另一个 .R 文件调用它们。如果可以的话怎么办?

python - 制作一个 Python 脚本来加载目录中的所有 npy/npz 文件

javascript - 当鼠标不在链接上时,下拉菜单消失

javascript - 使用 Jquery 将行附加到嵌套的 HTML 表

javascript - 为什么 jQuery .addClass() 比直接修改 HTML 更有用

jQuery UI 可排序删除元素不起作用

python - 在 python 中,有没有办法从对象本身找到包含变量或其他对象的模块?

javascript - HighCharts 图形无法在 Internet Explorer 上运行

c# - VCCodeModel 不在 VCCodeModel 命名空间中?

xslt - xsl :template match attribute: how related to default namespace