简体   繁体   English

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

[英]Remove the click event from a single Div element

I have added a mousedown handler to all the divs inside a parent div, like this: 我已经将mousedown处理程序添加到父div内的所有div中,如下所示:

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

Now I want to remove the mousedown handler after the button is clicked, for that particular div. 现在,我想为该特定div单击按钮后删除mousedown处理程序。 How do I do that? 我怎么做? Removing the attr mousedown doesn't seem to work. 删除attr mousedown似乎无效。

Use the off method: 使用off方法:

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

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

You could also use the one method instead. 您也可以改用one方法。 It will automatically remove your event handler at the first time it is triggered: 它将在第一次触发时自动删除事件处理程序:

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

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

use .off Description: Remove an event handler. 使用.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');
});

instead of : 代替 :

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

use : 采用 :

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

or 要么

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM