An outlet for my obsession with technology
jQuery, Ajax, prepend and events (onclick?)
Ok, why in gods name can’t I figure this out!
Adding simple elements to the DOM works…no problem.
1: new_elem = '<a href="#" onclick="alert(\'alert\')">MyAdd</a>';
2: var test = $(new_elem);
3: $('#home_column').prepend(test);
I end up with a link…when I click it…I get an alert.
BUT!….when I have the same code in the success of an ajax call the elements are added to the DOM but nothing happens when I click on it!…I know! Crazy right?
1: $.ajax({
2: success: function(data){
3: new_elem = '<a href="#" onclick="alert(\'alert\')">MyAdd</a>';
4: var test = $(new_elem);
5: $('#home_column').prepend(test);
6: },
7: url: 'http://twitter.com/statuses/friends_timeline.json' + app.twitter.since_parameter()
8: });
So….this code is placed in $(document).ready….it runs…the element is added to the DOM…life is good right? NOPE! I can’t click on it…well I can but nothing happens.
I think my ajaxSetup is pretty standard...
1: $.ajaxSetup({
2: mode:'queue',
3: beforeSend: function(xhr) {
4: var auth = $.base64Encode(USERNAME + ":" + PASSWORD);
5: xhr.setRequestHeader("Authorization", "Basic " + auth);
6: xhr.setRequestHeader("Cookie", "");
7: xhr.setRequestHeader("If-Modified-Since", 'Sun, 1 Jan 2007 18:54:41 GMT');
8: },
9: dataType: "json",
10: type: "GET"
11: });
Related posts:
| Print article | This entry was posted by Eric Polerecky on January 13, 2009 at 10:41 pm, and is filed under JavaScript, jQuery. Follow any responses to this post through RSS 2.0. You can leave a response or trackback from your own site. |
about 1 year ago
delegation is how I coded around the “issue” but I don’t yet understand why a programmatic added element would work just fine but a programmatic added after ajax element would not work…shouldn’t the results be consistent?
about 1 year ago
http://docs.jquery.com/Release:jQuery_1.3
Live Events
jQuery now supports “live events” – events that can be bound to all current – and future – elements. Using event delegation, and a seamless jQuery-style API, the result is both easy to use and very fast.