Joel
Joel

Reputation: 457

Binding click event to appended link with jQuery

I've got a lightbox that uses jQuery's $.ajax to retrieve data.

If i get back no data, then I append a "no data found" message to my list, and a link to reset the search parameters. Basically I'm trying to add a .click() event to a link that I've appended.

The problem is that the function is running immediately, not waiting for a click event.

So when I execute this, the "no data found message" appears briefly and then is replaced by the default results.

function getImages(/* parameters ... */) {
    // other code...
    // if no results:
    $('div#imageLightBox ul.thumbList').append('<li>Sorry, no images found. <a href="#" id="clearSearchLink">Clear search</a>.</li>');
    $('a#clearSearchLink').click(new function() {
        alert("clearSearchLink");
        // code that resets the search parameters ...
        getImages('', '', $('#lightBoxPageSize').val(), 1); // <-- calls the function that contains this code.
    });
};

Upvotes: 1

Views: 260

Answers (1)

bobince
bobince

Reputation: 536489

click(new function() {

Just ‘function’.

This is a function expression, not a constructor; ‘new Function()’ with the capital F is the explicit constructor version, which you generally don't want to use as it takes and evaluates a string argument every call, which is pretty yucky (and slower).

What is happening is the function expression is creating a new function, then the ‘new’ operator is calling it with a newly-created Object as this (which is what new actually does).

Upvotes: 3

Related Questions