javascript - 使用需要作为按钮属性的参数的函数来限制按钮单击 - Javascript
问题描述
努力把我的头缠在这个周围。我刚刚深入研究了节流、关闭和避免全局变量的世界。
我有多个按钮:
<a content_name="home" class="menuLink"><span>HOME</span></a>
我想限制每个按钮的点击,直到 getContent 完成(为了这个问题,我们假设它需要 200 毫秒)。
我的JavaScript:
function getContent(contentName) {
//Does some things
}
// Simply throttle function
function throttle(callback, limit) {
var throttleLock = false;
console.log('throttling: ' + throttleLock);
return function () {
if (!throttleLock) {
callback.call();
throttleLock = true;
setTimeout(function () {
throttleLock = false;
}, limit);
}
}
};
// Event listeners for the buttons
var menuButtons = document.getElementsByClassName("menuLink");
var menuBtnClick = function() {
var attribute = this.getAttribute('content_name');
getContent(attribute);
};
for (var i = 0; i < menuButtons.length; i++) {
menuButtons[i].addEventListener('click', throttle(menuBtnClick, 500), false);
}
如果我这样重构(没有节流功能)一切正常,除了它不节流(显然):
for (var i = 0; i < menuButtons.length; i++) {
menuButtons[i].addEventListener('click', menuBtnClick, 200), false);
}
日志错误是:
Uncaught TypeError: this.getAttribute is not a function
at menuBtnClick ([this is my filename and line])
at HTMLAnchorElement.<anonymous> ([this is my filename and line])
我知道油门函数正在触发(控制台日志),但它似乎没有触发回调,并且throttleLock 的值仍然为假。
请帮忙,我确定我做错了什么,我想学习。如果有任何替代这种尝试的方法,请开火,我全神贯注。
谢谢。
解决方案
只需将上下文应用于回调调用:
callback.call(this);
这是示例: https ://jsbin.com/yekimaqelo/1/edit?html,js,console,output
推荐阅读
- c++ - 尝试引用已删除的函数_gmock
- javascript - 清除屏幕通知
- javascript - 从表中的每一行中获取前三个文本(cheerio)
- ruby-on-rails - 使用 toshimaru / jekyll-toc 在 jekyll 站点上自定义自动生成的 TOC
- flutter - 如何从颤动的模态底部表中获取数据?
- validation - Yii2 - 没有 $form->field() 的 AJAX 验证
- kubernetes-helm - 使用 Kubernetes Ingress Nginx 的 GRPC 服务器没有响应
- git - 如何将 ssh 密码添加到 Docker 并在使用后将其删除?
- powershell - 如何在备份脚本期间记录复制的项目?
- delphi - 在 RTL 系统上强制英语语言任务对话为 LTR