0

Possible Duplicate:
Event binding on dynamically created elements?

I add some links through an if-statement, that looks like this:

if(jQuery.inArray(keywords[i].toLowerCase(), wordFilter) == -1) {
    $('p.suggestions').append('<a href="#" class="suggestion">' + keywords[i] + "</a> ");
}

The links are correctly added. I register a click on every link with the suggestion class like this:

$('p.suggestions a').click(function(e) {
    e.preventDefault();
    t.add($(this).text());
});

It worked fine when I hardcoded a link in my html-file, and the click was registered and t.add() was executed. But when the links are added with the if-statement, it doesn't work anymore. Anyone got a clue how this comes?

Community
  • 1
  • 1
Veltar
  • 741
  • 2
  • 14
  • 30
  • 1
    This is definitely the most asked *"problem"* here on S.O. There's at least 2000 same questions with same answers. Just take a look at `.on()` method. IT should be closed as exact duplicate. – Roko C. Buljan Dec 29 '12 at 14:53

4 Answers4

2

Use jQuery on

$(document).on('click','p.suggestions a',function(e) {
    e.preventDefault();
    t.add($(this).text());
});
Anoop
  • 23,044
  • 10
  • 62
  • 76
1

You should bind it "live" with on

$(document).on( 'click', 'p.suggestions a', function(e) {
    e.preventDefault();
    t.add($(this).text());
});

While binding only via click, the handler is binded to all selected (means: all existing ones) elements. If there occurrs a new element, it doesn't know anything about the handler. With so called "live" binding, you can also bind handlers to elements, that are inexistent now, by listening to special selectors.

bukart
  • 4,906
  • 2
  • 21
  • 40
1

When you add elements dynamically, you better bind the events with jQuery's on -> http://api.jquery.com/on/

Formerly, live and delegate was the recommendation, but now on is the way to go.

David Müller
  • 5,291
  • 2
  • 29
  • 33
0

For Dynamic content use on() function Jquery! live() and delegate() are deprecated

$(document).on('click','p.suggestions a',function(e) {
    e.preventDefault();
    t.add($(this).text());
});
Muhammad Talha Akbar
  • 9,952
  • 6
  • 38
  • 62