Becareful with jquery on or bind event.

When you do jQuery and sometime you would bind some functions on an event outside appended DOM elements, and rerun the function again like this:

<ul>
 	<li>test</li>
 	<li>test</li>
 	<li>test</li>
</ul>
<button></button>

for example we want to change the text to something else when we click on each of the li, maybe lets change to “run test …”;

function changeText(){
  $(this).find('p').text("run test");
}

$('li').on('click', changeText);
//$('li').bind('click', changeText);

now you want append a new li and allow function on that appended li like this:

$('button').click(function(){
  $('ul').append('<ul><li>New text</li></ul>');
  $('li').on('click', changeText);
})

 

this situation it works well, however what actually happened is that you create the function two times on each event (‘click’), if you click button again second time, you create three function for each li click, and so on…
so what you want to do is off the click first, then on again, like this.

$('button').click(function(){
  $('li').off('click');
  $('ul').append('<ul><li>New text</li></ul>');
  $('li').on('click', changeText);
})

 

let me know if you have anything to comment below.