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

时间:2013-10-29 15:42:30

标签: javascript jquery

我已经为父div中的所有div添加了一个mousedown处理程序,如下所示:

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

现在我想在单击按钮后删除mousedown处理程序,用于该特定div。我怎么做?删除attr mousedown似乎无效。

3 个答案:

答案 0 :(得分:3)

使用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/

答案 1 :(得分:1)

使用.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');
});

答案 2 :(得分:1)

而不是:

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

使用:

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

$(this).off('mousedown');
相关问题