Monday 15 April 2013

jquery - on() does not do the live() job for me -


This is outlined on the jQuery website .live () method is no longer recommended.
I was trying to use the .on () event but I hope it does not show up. Using .live for the following scenario, I have no problem.

I have found a field for which I use an autocomplete plugin:

What this does is, every time you are about to enter an entry, you Put it in a field (generated by the plugin) such that when you enter the first entry and it is completed, the second time you are entering the input, another new area is created with the same class:

  & lt; Li id = "select" & gt; & Lt; Input type = "text" autocomplete = "off" size = "0" square = "input" & gt; & Lt; / Li & gt;   

What I'm trying to do, is a generator on paste handler, so every time I paste something, that is the input, it's a tag with its tag The entry (which is not related to it, is the current issue anyway) when I use Live event works as expected, it not only handles my paste for the first time, but also for future pastes. But when I change it, it only works for the first paste. The following is my code:

  $ (document) .ready (function () {$ (".input"). Live ('paste', function (event) {var element = this; SetTimeout (function () {var text = $ (element) .val (); addItem (text);}, 10);});}); Can anyone explain why this is happening?   

P> You put it in the field (generated by the plugin), such as when you enter the first entry The second time when you are entering the input, another new area is created with the same class

It sounds like a dynamic element Using it, bubbling that event on document and then paste . The function was reworked when the input was on element.

By changing it like a simple () : $ (".input"). ('Paste', the function (event) {} will not be repeated.

This will be just a simple dam and as soon as the element is dynamically changed / added again It is, as soon as the element was removed, even then the bound events went away, even if it was added again.

To repeat live () for dynamic elements You must use the at () delegation, which will allow you to bind the event

) .ready (function () {$ (".input"). Live ('paste', function (event) {var element = this; setTimeout (function) (var text = $ (element ) .val (); AddItem (text);}, 10);});});

To use with this type of representative () :

  $ (document) .ready ( Function () {$ (document) .on ("paste", ".input", function (event) {var element = this; SetTimeout (function () {var text = $ (element) .val (); addItem ( Text;), 10);});});   

The above event is now bound to the document , but . Input element paste is given on code>.

Instead of document you should bind to the nearest static parent element, for example body or fixed parents with proximity, such as:

  $ ('body'). ("Paste", "Input", Function (Event) {...}   

Which is the closest stable parent of the .input element, However, the document or body will close the course.

No comments:

Post a Comment