javascript - Event fails to fire after DOM change in jQuery 1.9 -


i trying code cancel button user input. user able edit item after double-clicking on , cancel button allow user cancel action.

the double-clicking part of code works great, text-input box appears cancel button attached. since dom has changed, jquery no longer select new element, , therefore when cancel button clicked event not fired. illustrate, code following:

<div id="main"> <ul class="todolist">     <li id="todo-1" class="todo">         <div class="text">new todo item. doubleclick edit          </div>         <div class="actions"> <a href="#" class="edit">edit</a></div>     </li> </ul> </div> 

var currenttodo; $('.todo').on('dblclick', function () {     $(this).find('a.edit').click(); });  $('.todo a').on('click', function (e) {     e.preventdefault();     currenttodo = $(this).closest('.todo'); });  $('.todo a.edit').on('click', function () {      var container = currenttodo.find('.text');      if (!currenttodo.data('origtext')) {         // saving current value of todo can         // restore later if user discards changes:          currenttodo.data('origtext', container.text());     } else {         // block edit button if edit box open:         return false;     }      $('<input type="text">').val(container.text()).appendto(container.empty());      container.append(         '<div class="edittodo">' +         '<a class="cancel" href="#">cancel</a>' +         '</div>');  });  // cancel edit link:  $('.cancel').on('click', function () {     alert("oops"); }); 

or here: http://jsfiddle.net/s7f83/42/

my question therefore, how can 'bind' event after dom has changed? thank much

in example events bound controls exist @ moment of binding, , match selector. if actions apply newly created controls, shall bind event document itself. highest level dom element, events lower levels propagate it.

at second parameter give context, if event received context function fire.

$(document).on('dblclick', '.todo', function () {     $(this).find('a.edit').click(); }); 

i won't cite whole code, idea one.

binding listeners document encouraged doesn't create many bindings many controls have, 1 top level binding, waits events propagate on dom tree. more info on optimalization: http://24ways.org/2011/your-jquery-now-with-less-suck/


Comments

Popular posts from this blog

c# - Send Image in Json : 400 Bad request -

javascript - addthis share facebook and google+ url -

ios - Show keyboard with UITextField in the input accessory view -