开发者

print array with js and add html with jQuery

i want to 开发者_如何转开发print an array with js and just add to every element some data with html()

the code i use is :

<script type="text/javascript">

$(document).ready(function() {
 var testArray = ["test1","test2","test3","test4"];

 for(var i=0;i<testArray.length;i++){
 document.write(" " +testArray[i]+"<br />").html("is the best");
 }
});

</script>

but it doesnt works.


HTML:

<div id="myDIV"></div>

JS:

$(document).ready(function() {
    var testArray = ["test1","test2","test3","test4"];
    var vPool="";
    jQuery.each(testArray, function(i, val) {
        vPool += val + "<br /> is the best <br />";
    });

    //We add vPool HTML content to #myDIV
    $('#myDIV').html(vPool);
});

Update: Added demo link: http://jsfiddle.net/aGX4r/43/


Syntax problem mate!

Let me get that for you!

// first create your array
var testArray = ["test1", "test2", "test3", "test4"];

// faster ready function
$(function(){

 for( var i=0; i<testArray.length; i++ ) {

  current = testArray[i] + '<br />' + 'is the best'; // this is a string with html in it.

  $(current).appendTo("body"); // add the html string to the body element.

 }

});


First. document.write it's not a good practice.

Then, you code have a little error: Function (as in document.write) doesn't have html method. Thats a jQuery method.

So, in order to print the array in the body, you could do:

$('p').html(["test1","test2","test3","test4"].join('<br />')).appendTo(document.body);


It's a little difficult to tell what you want to do, but if you want to append to an element in your DOM, use jQuery.append();

for(var i=0;i<testArray.length;i++) {
    jQuery('#mydiv').append(testArray[i]);
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜