JQuery.on () method does not see new elements

I get a JSON element and build a list of its elements as follows:

getTitles: function(data) { data = data || {}; var list = []; $.getJSON( '/titles', data, function(data) { $.each(data.data, function(key, val) { list.push( '<li><a href="'+ val.href +'">'+ val.title +'</a><span class="count">'+ val.count +'</span></li>' ) }); $('#title-items').html(list.join('')); } ); } 

And I am binding a click event for a elements like this:

 $('a').on('click', function(e) { alert('clicked'); e.preventDefault(); }); 

Old a elements show a warning, but new follow URLs. Event handler does not work for new ones. How can I solve this?

+46
javascript jquery javascript-events event-handling jquery-events click
Dec 27 2018-11-12T00:
source share
3 answers

You are not using the correct code to get live functions.

 $('#title-items').on('click', 'a', function(e) { alert('clicked'); e.preventDefault(); }); 
  • First, select the common ancestor element ( #title-items in this example). You can use document here too if you want to process all elements of a .
  • Pass in the type of event ( on ), then the subselector ( a ), and then the callback function for the event.

Now that the click events are painted over to #title-items , it checks to see if the element is an a element, and if so, start the callback.

+132
Dec 27 '11 at
source share

You want to use delegation delegation to capture events caused by events that are present in the DOM at any given time:

 $(<root element>).on('click', 'a', function(e) { alert('clicked'); e.preventDefault(); }); 

UPDATE In this example, the <root element> is the ancestor of the links to which you are bound that are present in the DOM during the binding.

The basic idea is that since we cannot attach an event handler to a DOM element that is not already in the DOM, we attach an event handler to the parent element and wait for the event to drop to the parent element. After the event reaches the ancestor event, the event.target property is checked to see what was the element with the original click.

+13
Dec 27 '11 at 23:45
source share

You can use the arrival.js library (it uses MutationObserver inside.)

 document.arrive('a', function(){ // 'this' refers to the newly created element var newElem = this; }); 
0
Feb 26 '15 at 6:00
source share



All Articles