开发者

Why can't I use the return from an insertAfter as a regular jQuery object?

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.


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)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜