Appending an array of jQuery objects to another jQuery node
In version 1.3.2 of jQuery, the following works:
$('<span/>').append(
$([
$('<span/>').append(
$('<a>').attr('href', 'http://google.com').text('Google')
),
$('<span/>').text('Foo')
])
)
It seems that i开发者_C百科n jQuery 1.4.2, the $([...]) fails silently. I need this code to be compatible with both versions of jQuery since our unit tests are forced to run 1.3.2, but the main application uses jQuery 1.4.2. Any ideas?
Try using .get(0)
to grab the actual element to be added to the array. Seems to work:
Try it out: http://jsfiddle.net/TFY22/
(You can switch the jQuery version on the left in jsFiddle, then click Run at the top.)
var test = $('<span/>').append(
$([
$('<span/>').append(
$('<a>').attr('href', 'http://google.com').text('foo')
).get(0), // Get DOM element
$('<span/>').text('Google').get(0)// Get DOM element
])
);
$('body').append(test);
EDIT: With regard to the comments below, there are simpler approaches.
This will create the entire structure at once.
$('<span><span><a href="http://google.com">foo</a></span><span>Google</span></span>');
If you have any dynamic data to include, you can concatenate it in, just be aware that there are security concerns if the source of the data is unknown.
http://jsfiddle.net/TFY22/1/
var text = 'foo';
$('<span><span><a href="http://google.com">' + text +
'</a></span><span>Google</span></span>');
Or take a more verbose approach, and create each element separately, and append:
http://jsfiddle.net/TFY22/2/
var $top = $('<span/>');
var $a = $('<a/>').attr('href','http://google.com').text('foo');
$('<span/>').append($a).appendTo($top);
$('<span/>').text('Google').appendTo($top);
Or chain your .append()
calls to give a structured appearance:
http://jsfiddle.net/TFY22/4/
var test = $('<span/>')
.append($('<span/>')
.append($('<a>').attr('href', 'http://google.com').text('foo'))
)
.append($('<span/>').text('Google'));
$('body').append(test);
精彩评论