Let's say we have this unidentified DIV
<div class="class-occurs-many-times-on-page">foo</div>
and we want to place right after it another unidentified DIV that contains dozens or hundreds of SPAN elements:
<div class="a-class-that-occurs-many-times-on-page">foo</div>
<div class="another-class-that-occurs-many-times-on-page">
<span class="latin">lorem</span><span class="latin">ipse</span>
<span class="swedish-chef">føø</span><span class="swedish-chef">bår</span>
.
.
.
<span>...</span>
</div>
And we have added the first unidentified DIV and want to add the SPAN-container DI开发者_如何学运维V in this way:
values = [{word: "lorem", cls: "latin"}, {word: "ipse", cls: "latin"},
{word:"føø",cls:"swedish-chef"}, {word:"bår",cls:"swedish-chef"}];
$("#" + someParentElement).append(
$("<div></div>").addClass("a-class-that-occurs-many-times-on-page").text("foo").after(
$("<div></div>").addClass("another-class-that-occurs-many-times-on-page").append(
function(index, html){
// how to wrap each value in the values array in a span
// and inject each of those spans into this DIV?
}
)
)
);
Is this approach possible, and if so, what does the function inside the .append() method invocation have to do on each iteration of the values array, if the goal is to wrap each of the values in the array in a SPAN and inject that span into the container?
Thanks
values = [{word: "lorem", cls: "latin"}, {word: "ipse", cls: "latin"}, {word:"føø",cls:"swedish-chef"}, {word:"bår",cls:"swedish-chef"}],
len = values.length,
$ctn = $('<div/>', {
class: 'another-class-that-occurs-many-times-on-page'
}),
buildarr = [];
while(len--){
buildarr.push('<span>');
buildarr.push(values[len].word);
buildarr.push(values[len].cls);
buildarr.push('</span>');
}
$ctn.append(buildarr.join('')).appendTo(document.body);
That is just a suggestion like you could accomplish that kind of task. It assumes the order in which we have to fill the array is irrelavant (by looping with the fastest way, reversed while
). If the order is important use a standard for loop
.
精彩评论