Remove jQuery delegated event handler on specific object

自古美人都是妖i 提交于 2019-11-29 11:08:28

After having read thru on the web, the answer is you can't! You can either remove all or none. A workaround could be something like the following.

$(document).on('click', '.btn', function (ev) {
    alert('pressed');
    $(this).removeClass("btn");
});

Demo@Fiddle

Sample HTML:

<button class="btn">One</button>
<button class="btn">Two</button>
<button class="btn">Three</button>

Question: Do you have to use the delegated events? LIke LShetty said, it is not possible to remove a delegated event for a single element. You either remove the entire event delegation, or leave it. You could try using a different selector instead like in this example

$('button').on('click', function(ev) {
    $('#output').append('Clicked! ');
    $(this).off('click');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<button>One</button>
<button>Two</button>
<button>Three</button>
<div id="output"></div>

In addition to what lshettyl said (the current top post) - an additional work around is to bind a new event listener directly to the element that you're trying to remove the listener and call stopPropagation() therein.

What this will do is prevent the event from traveling up the DOM and reaching the event handler that is initially bound to the document. Also this will allow you to keep some functionality on the button click, such as an alert to the user that this button has already been clicked - or something to that effect.

$(document).on('click', 'button', function(ev) {
    // Your logic to occur on button click

    // Prevent further click on just this button
    $(this).click(function(event) {
        event.stopPropagation();
    }):
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!