gpt4 book ai didi

javascript - 如何将多个匿名 jquery 函数转换为单个命名函数?

转载 作者:行者123 更新时间:2023-12-02 19:19:17 28 4
gpt4 key购买 nike

是否可以将以下四个匿名 jquery 函数转换为一个传递参数的函数?

这就是我所拥有的...

    dropZone.addEventListener("dragenter", this.dragEnter, false);
dropZone.addEventListener("dragover", this.dragOver, false);
dropZone.addEventListener("dragleave", this.dragLeave, false);
dropZone.addEventListener("drop", this.dragDrop, false);

...

this.dragOver = function(ev) {
ev.stopPropagation();
ev.preventDefault();
this.className = "dragover";
}

this.dragLeave = function(ev) {
ev.stopPropagation();
ev.preventDefault();
this.className = "dragleave";
}

this.dragEnter = function(ev) {
ev.stopPropagation();
ev.preventDefault();
this.className = "dragenter";
}

this.dragDrop = function(ev) {
ev.stopPropagation();
ev.preventDefault();
this.className = "dragdrop";
}

我正在寻找功能类似于...的东西

    dropZone.addEventListener("dragenter", dropEvent(this,"dragenter"), false);
dropZone.addEventListener("dragover", dropEvent(this,"dragOver"), false);
dropZone.addEventListener("dragleave", dropEvent(this,"dragLeave"), false);
dropZone.addEventListener("drop", dropEvent(this,"dragDrop"), false);

...

function dragEvent(ev, label) {
ev.stopPropagation();
ev.preventDefault();
this.className = label;
}

最佳答案

您可以使用部分应用的函数来做到这一点:

function dragEvent(that, label) {
return function(ev) {
ev.stopPropagation();
ev.preventDefault();
that.className = label;
}
}

您可以在此处阅读有关 javascript 部分应用的更多信息:http://benalman.com/news/2012/09/partial-application-in-javascript/

关于javascript - 如何将多个匿名 jquery 函数转换为单个命名函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12733307/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com