views:

35

answers:

1

I'm trying to insert a link after form elements to clear them.

This demo code with headings doesn't work:

h2 = $('h2');
clickytest = $('<a href="#" class="clicky">click me</a>').insertAfter(h2).click(function() {
  $(this).append('foo');
});

But this does:

h2 = $('h2');
clickytest = $('<a href="#" class="clicky">click me</a>').insertAfter(h2);
$('a.clicky').click(function() {
  $(this).append('foo');
});

The only difference is I've gone back and re-selected the new elements, rather than use what insertAfter returns.

If on the other hand there is only one H2 in the whole document, then the first version works. What's going on? I've tried playing with each() but I'm not sure exactly what jQuery is doing here.

+1  A: 

I would stick to attaching your event handlers to the elements before moving them, since some attachment methods differ on which context they return. Attach the click before moving on for it to always work, like this:

$('<a href="#" class="clicky">click me</a>').click(function() {
  $(this).append('foo');
}).insertAfter('h2');​

See here for a working sample (multiple <h2> elements)

Nick Craver