提问人:Meek 提问时间:4/4/2018 更新时间:4/4/2018 访问量:12
如何在 onclick 和 windows.resize 上运行命名空间函数
How to run namespaced function onclick and on windows.resize
问:
我有这个功能,可以在单击页眉时折叠/展开页脚中的项目。它按预期工作。但是,我需要对函数进行命名空间,但我无法让它工作。
现有功能:
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>
答:
0赞
Rory McCrossan
4/4/2018
#1
当您为函数提供参数时,您需要将其包装在另一个匿名函数中:
jQuery('.footer-heading').on('click', function(e) {
globalFooter.collapseFooter(this, e);
});
评论