Why can't I access my jQuery collection once it has been used to wrap another element?
Look at this code:
var b = $('<div id="b" />');
$('#a').wrap(b);
b.css({ border: '5px solid red' });
jsFiddle.
The element stored under b
will not have a border.
Is there any way to access b
still once it has been used to wrap anoth开发者_如何学运维er element?
Or should I do b = $('#b')
again?
I don't think jQuery actually uses the same instance of "b" to wrap it. You would need to overwrite "b" with the one that was created to do the wrap.
var b = $('<div id="b" />');
b = $('#a').wrap(b).parent();
b.css({ border: '5px solid red' });
I suppose the reason is that if a
was a class instead of an ID, and there were several of them, you wouldn't be able to use the same element to individually wrap each .a
.
So it must make a clone of b
that it uses to do the wrap.
var b = $('');
$('#a').wrap(b).css({ border: '5px solid red' });
The b contain the element in memory, after DOM append, you send b to DOM at second line and before call css() by the element referenced by "b" and not by the DOM match.
精彩评论