开发者

split var and create N of div with array key in html

开发者 https://www.devze.com 2023-03-20 20:40 出处:网络
Thanks开发者_如何学JAVA for reading. if we have: var letters = \'a b c h\'; // ... how can we get this result:

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:

  1. The "letters" array is what you're accustomed too, straight forward.
  2. 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.
  3. I use jQuery's .each() method applied to the result of the String.split (which results in an array of letters). Each then begins iterating over each unique letter
    1. For each letter, we establish a new div
    2. We use the object parameter of jQuery to apply both the class and the body of the new element
    3. 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]));
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号