split var and create N of div with array key in html
Thanks开发者_如何学JAVA for reading.
if we have: var letters = 'a b c h'; // ...how can we get this result:
<div class="box">
<div class="letter">a</div>
<div class="letter">b</div>
<div class="letter">c</div>
<div class="letter">h</div>
<!-- ... -->
</div>
(In DOM ready) something like:
var letters = 'a b c h k w x'; // 7 letters (can be more...)
var char = letters.split(' ');
var nOfChars = char.length;
var divLetter = $('<div class="letter" />');
for(var char = 0; char < nOfChars; ++char) {
$('.box').append( divLetter );
$('divLetter').html( char );
}
(Far from good, I know. please help)
var letters = 'a b c h';
// don't know if you want to append to body or now, but you can fool with
// the placement of the "Wrapper" div here.
var divLetter = $('<div>',{ class: 'letter'}).appendTo('body');
$.each(letters.split(' '),function(i,e){
$('<div>',{
class: 'letter',
html: e
}).appendTo(divLetter);
});
demo
Broken down, it's the following:
- The "letters" array is what you're accustomed too, straight forward.
- The div is another thing you're already using, but I've used
.appendTo
to attach it to DOM. You can place this anywhere, or have the div already on the page--up to you. - I use jQuery's
.each()
method applied to the result of theString.split
(which results in an array of letters). Each then begins iterating over each unique letter- For each letter, we establish a new div
- We use the object parameter of jQuery to apply both the class and the body of the new element
- We call the
appendTo
to attach it to the original div
All said and done, we have the result you're looking for.
Try this out:
http://jsfiddle.net/sexDH/ (haha)
var letters = 'a b c h k w x', // 7 letters (can be more...)
chars = letters.split(' '),
nOfChars = chars.length,
$divLetter = $('<div class="letter" />'),
letterFragment = document.createDocumentFragment();
for (var i=0; i<nOfChars; i++) {
letterFragment.appendChild( $divLetter.clone().html(chars[i])[0] );
}
$('.box').append( letterFragment.cloneNode(true) );
var string = "a b c d";
var parts = string.split(" ");
for(key=0;key < parts.length;key++)
{
$(".box").append($("<div>").addClass("letter").html(parts[key]));
}
精彩评论