javascript - jQuery 3.x .off() after .on() -
i used .off() method after .on() method .click() method.
i'm confused why click() event fires!
$('span').on('click', function () { $('p').text("you clicked!") }); $('span').off('click', function () { $('p').text("ha ha ha!") });
span{ background-color:#ac0; padding:5px; cursor:pointer; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <span>click me!</span> <p>*****</p>
you've misunderstood function @ end of off()
method. isn't callback, it's event handler.
that function supposed same event handler function 1 set initially. done way can remove individual click handler.
function handlera(e) { console.log('heard a'); } function handlerb(e) { console.log('heard b'); } // add both handlers click events $('span').on('click', handlera); $('span').on('click', handlerb); // remove first click event only, leaving second $('span').off('click', handlera);
the above log heard b
when clicked.
to remove all click handlers, need omit function entirely.
$('span').off('click');
Comments
Post a Comment