第一次点击后jQuery取消绑定

bra*_*ert -1 javascript jquery javascript-events

这会导致多个按钮执行操作:

$(document).on("click", ".file-this-email", fileThisEmail);
Run Code Online (Sandbox Code Playgroud)

fileThisEmail运行时,我想只从当前删除它(还有其他的网页上仍然需要它):

window.fileThisEmail = function(e) {
  console.log('this was clicked');
}
Run Code Online (Sandbox Code Playgroud)

我试过了off,但似乎无法把它弄好.有任何想法吗?

use*_*654 6

在这种情况下,您必须使当前元素不再与".file-this-email"选择器匹配.

$(document).on("click", ".file-this-email", function() {
    console.log('this was clicked');
    $(this).removeClass("file-this-email");
});
Run Code Online (Sandbox Code Playgroud)

另一种方法是使用相同的概念向选择器添加过滤器.

$(document).on("click", ".file-this-email:not(.clicked)", function() {
    console.log('this was clicked');
    $(this).addClass("clicked");
});
Run Code Online (Sandbox Code Playgroud)

或者,不要在这种特殊情况下使用委托.委托不是一种取代直接绑定的新技术,它只是绑定事件的另一种方式.如果使用正确,它可以使代码更有效.反之亦然; 如果使用不正确,它可能会使代码非常臃肿.

$(".file-this-email").on("click", function () {
    console.log("this was clicked");
    $(this).off("click");
});
// or even better (thanks @overachiever):
$(".file-this-email").one("click", function () {
    console.log("this was clicked");
});
Run Code Online (Sandbox Code Playgroud)