Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
118
rated 0 times [  124] [ 6]  / answers: 1 / hits: 32821  / 13 Years ago, tue, december 27, 2011, 12:00:00

I'm getting a JSON element and building a list from its items like this:



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'm binding click event for a elements like this:



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


Old a elements shows alert but new ones follow URL. Event handler doesn't work for new ones. How can I solve this?


More From » jquery

 Answers
2

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



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



  1. First, select your common ancestor element (#title-items in this example). You can use document here too if you want to handle all a elements.

  2. Pass the event type (on), then the sub selector (a), and then the callback function for the event.



Now, when click events bubble up to #title-items, it will check to see if the element is an a element, and if so, fire the callback.


[#88348] Monday, December 26, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
nestorjarettg

Total Points: 451
Total Questions: 108
Total Answers: 108

Location: Rwanda
Member since Thu, Feb 10, 2022
2 Years ago
;