从单个 Div 元素中删除单击事件

Remove the click event from a single Div element

本文关键字:删除 单击 事件 元素 单个 Div      更新时间:2023-09-26

我已经为父div内的所有div添加了一个鼠标向下处理程序,如下所示:

$productContainer.children(".button").on('mousedown', function(){
    var index = $(this).index();
    console.log("Clicked button at " + index);
    // this doesnt work
    $(this).removeAttr('mousedown');
});

现在我想在单击按钮后删除该特定div 的鼠标向下处理程序。我该怎么做?删除attr mousedown似乎不起作用。

使用 off 方法:

$productContainer.children(".button").on('mousedown', function(){
    var index = $(this).index();
    console.log("Clicked button at " + index);
    $(this).off('mousedown');
});

更多信息: http://api.jquery.com/off/

您也可以改用 one 方法。它将在第一次触发事件处理程序时自动删除它:

$productContainer.children(".button").one('mousedown', function(){
    var index = $(this).index();
    console.log("Clicked button at " + index);
});

更多信息: http://api.jquery.com/one/

而不是 :

$(this).removeAttr('mousedown');

用:

$(this).unbind('mousedown');

$(this).off('mousedown');

使用.off 说明:删除事件处理程序。

$productContainer.children(".button").off('mousedown');
$productContainer.children(".button").on('mousedown', function(){
    var index = $(this).index();
    console.log("Clicked button at " + index);
    // this doesnt work
    $(this).removeAttr('mousedown');
});