The .off()
is mainly used to prevent duplication of the same action, see the example, SEM .off()
:
function button(e){
if($(e).hasClass('comOff')){
$(e).off();
}
$(e).on('click', function() {
button($(this));
alert($(this).text());
});
}
button('.semOff');
button('.comOff');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="semOff">SEM OFF</button>
<br>
<hr>
<button class="comOff">COM OFF</button>
In this example, which is not one of the best, when you click on "NO OFF" more than once it will display more than one alert. This is because the previous action was not turned off, so another one will be added. When you use the .off()
you will remove any .on()
that was previously added.
When you use: $(document).off()
, means that ALL .on()
applied in the document
will be removed when you specify $(document).off('evento', 'elemento', nomeFuncao);
you just that will be removed!
That’s the difference.
I particularly prefer to use $('div button.salvar').on('click', [...])
for example, instead of using the document
.
Off
I don’t know and never used, and I useOn
is aBind
. Example$('div#botao').on('click', function() { alert(1); });
or$('div#botao').bind('click', function() { alert(2); });
... see test: http://codepen.io/KingRider/pen/OXoVVB– KingRider
Yes. But starting with version 1.7 of jQuery he recommends using the ON method to add event handlers to Document. The BIND method should only be used in summers prior to 1.7 of jQuery. Reference: http://api.jquery.com/bind/
– alan
I understand, and I researched
off()
is equalunbind()
, but has problem its previous version? and why does not use pure javascript rss– KingRider
From what I read in the documentation. bind() and unbind() were replaced by on and off methods starting with jQuery version 1.7. As for why I didn’t do it with pure javascript, it’s because I don’t know how to do the same thing with pure javascript. I find it very practical and simple with jQuery. But if you think it’s simpler with javascript, I’d be happy if you could show me an example. ;)
– alan
Vish! I used javascript Pure until angular more practical kkkk, bind equals pure javascript addeventlistener, nothing easy and various type of element and object.
– KingRider