Question about jQuery .append()
Can anyone help me understand why this line doesn't create an image with a link:
var img = new Image();
$('#id').html('<开发者_C百科a href="http://google.com">').append(img).append('</a>');
I am setting the img attributes (src, alt... etc), I just took those lines out as they aren't relevant. Shouldn't this set the DIV's HTML to an HREF, then the image, then the closing A tag? This doesn't work for me, am I going about this the wrong way?
This should do it:
$(img).appendTo('#id').wrap('<a href="http://google.com" />');
Live demo: http://jsfiddle.net/simevidas/A4HqE/1/
jQuery's html()
will close your HTML elements automatically. See here: http://jsfiddle.net/simevidas/Ut2pQ/
Better solution:
$('<a href="http://google.com" />').append(img).appendTo('#id');
This solution is better because here the DOM is manipulated only once (when the ANCHOR is appended). In my original solution above, the DOM is manipulated twice (1. the IMG is appended, and 2. the ANCHOR is wrapped around the image).
Live demo: http://jsfiddle.net/simevidas/A4HqE/2/
Append is a tricky tag, some times it doesnt do what you expect.
In many cases its easer to use appendTo and actually BUILD the elements.
You have to append to something... its not like a string builder. Try:
$('<a>').attr({'id': 'aId' 'href': '[path for link]'}).appendTo('#divId');
$('<img>').attr('src', '[path to image]').appendto('#aId');
If you've already built your image using new Image()
you can use ITS id as the selector to append to the anchor... which can be appended to the div.
.append
takes a whole tag as an input, not the opening tag:
$('#id').html('<a href="http://google.com"></a>').append(img);
I would just do this:
$('#id').append($('<a>').attr('href', 'http://www.google.com').append(img));
Of course you have to set all the attributes for your image before anything will work correctly.
精彩评论