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.
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.
Share Improve this question asked Dec 13, 2010 at 18:31 t0st0s 1,2215 gold badges19 silver badges28 bronze badges 3- Where are you trying to output the html? – Nick Craver Commented Dec 13, 2010 at 18:34
-
2
Trying to chain a
document.write()
call with.html()
(which is a jQuery thing) makes absolutely no sense. Why are you usingdocument.write()
at all? – Matt Ball Commented Dec 13, 2010 at 18:38 - how im going to print without document.write() ? – t0s Commented Dec 13, 2010 at 18:48
4 Answers
Reset to default 6HTML:
<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/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]);
}
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1743765761a4503462.html
评论列表(0条)