javascript - Getting button click event handler to fire more than once -
javascript - Getting button click event handler to fire more than once -
i have quantity of rows:
var goal_index = 2;
and have function, create rows (default 2 rows) 2 buttons: trash (remove row), add(adding anoter row).
// creating goals var goals_creating = function(){ var goals_area = $('.goalsarea'), add_button = $('<span class="add_btn"></span>'), trash_button = $('<span class="trash_btn"></span>'); goals_area.html(''); for(var = 0, j = 1; < goal_index; i++, j++ ){ goals_area.append( '<div class="row" data-trashgoal = ' + + '>' + '<div class="col-lg-1">' + '<span class="trash_btn" data-trashgoal = ' + + '></span>' + '</div>' + '</div>' ); } // lastly trash tag var last_trash_btn = $('.trash_btn').last(); // insert after lastly trash button last_trash_btn.after(add_button); };
in lastly part of function, insert button (add) lastly row. , after running function:
goals_creating();
after running, created 2 events 2 buttons (add) , (remove):
$('.add_btn').on('click', function(){ goal_index++; goals_creating(); }); $('.trash_btn').on('click', function(){ var goal_to_del = $(this).data('trashgoal'); $('.row[data-trashgoal="' + goal_to_del + '"]').remove(); goal_index--; goals_creating(); });
but, working 1 time, after buttons remain non active, , not working. how can prepare bug? thanks
you have utilize event delegation. events "bubble" dom, , jquery makes easy exploit that:
$(document).on('click', '.add_btn', function() { /* before */ }); $(document).on('click', '.trash_btn', function() { /* before */ });
by doing that, you're saying, "when 'click' event reaches top of dom, , came element matches class 'add_btn', stuff." because you've installed 1 handler @ top of dom, won't go away , it'll grab events elements there origin elements added later.
the value of this
set in event handler set straight on element.
javascript jquery
Comments
Post a Comment