javascript 使用 js 打印数组并使用 jQuery 添加 html

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4432216/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 11:25:29  来源:igfitidea点击:

print array with js and add html with jQuery

javascriptjquery

提问by t0s

i want to print an array with js and just add to every element some data with html()

我想用 js 打印一个数组,然后用 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.

但它不起作用。

回答by eriksv88

HTML:

HTML:

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

JS:

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/

更新:添加演示链接:http: //jsfiddle.net/aGX4r/43/

回答by halfpastfour.am

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.

 }

});

回答by joksnet

First. document.writeit's not a good practice.

第一的。document.write这不是一个好习惯。

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

然后,您的代码有一个小错误:函数(如document.write)没有html方法。那是一个 jQuery 方法。

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

因此,为了在正文中打印数组,您可以执行以下操作:

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

回答by Kyle

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();

说你想做什么有点困难,但如果你想附加到 DOM 中的元素,请使用 jQuery.append();

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