2012-04-25 120 views
1

我試圖添加一個數組到網頁。我已經嘗試了幾個不同的代碼片段,但沒有一個能夠工作。我想輸出是類似像一個列表:將javaScript數組添加到HTML頁面?

的text1

文本2

文字3 ...

到目前爲止,我所使用的代碼是:

var i; 
var test = new Array(); 
test[0] = "text1"; 
test[1] = "text2"; 
test[2] = "text3"; 

// first attempt 
$('#here').html(test.join(' ')); 

// second attempt 
$(document).ready(function() { 
    var testList=""; 
    for (i=0;i<test.length; i++) { 
     testList+= test[i] + '<br />'; 
    } 
    $('#here').html('testList'); 
    songList=""; 
}); 

我對javaScript非常陌生,所以我不確定我是否犯了一個小錯誤,或者如果我以錯誤的方式做這件事。此外,以上是我的javaScript文件中的所有代碼的副本,一些網上的地方說我需要導入一些東西?我不確定!
感謝

+0

您是否在JavaScript控制檯中收到任何錯誤消息?你是否包含jQuery庫? – 2012-04-25 13:03:41

+2

與問題無關,但這是創建數組的一個骯髒的方法。只需使用'var test = [「text1」,「text2」,「text3」];' – 2012-04-25 13:05:07

回答

0

你有什麼作品,如果你從testList刪除單引號。但是,如果你想要一個實際的無序列表,你可以這樣做。 (here's a jsFiddle

var test = new Array(); 
test[0] = "text1"; 
test[1] = "text2"; 
test[2] = "text3"; 

// first attempt 
$('#here').html(test.join(' ')); 

// second attempt 
$(document).ready(function() { 
    var testList=$("<ul></ul>"); 
    for (var i=0;i<test.length; i++) { 
     $(testList).append($("<li></li>").text(test[i])); 
    } 
    $('#here').html(testList); 
    songList=""; 
}); ​ 
6

嘗試不帶引號:

$('#here').html(testList); 

- 或 -

$('#here').html(test.join('<br />')); 

另一種方法:

var html = '';         // string 
$.each(test,function(i,val){      // loop through array 
    var newDiv = $('<div/>').html(val);   // build a div around each value 
    html += $('<div>').append(newDiv.clone()).remove().html(); 
     // get the html by 
     // 1. cloning the object 
     // 2. wrapping it 
     // 3. getting that html 
     // 4. then deleting the wrap 
     // courtesy of (http://jquery-howto.blogspot.com/2009/02/how-to-get-full-html-string-including.html) 
}); 

$('#here').html(html); 

有可能是莫在後者中重新編寫代碼,但是如果您想添加ID,類或其他屬性,從長遠來看它會更乾淨。只需將其粘貼在一個函數中並修改jQuery即可。

4

嘗試改變線

$('#here').html('testList') 

$('#here').html(testList) 
+1

重複的答案:http://stackoverflow.com/a/10316269/782746 – binarious 2012-04-25 13:05:10

+0

vol7ron有點快;) – binarious 2012-04-25 13:06:21

+0

@Scott vol7ron第一次進入。 – 2012-04-25 13:06:32

0

這條線:

$('#here').html('testList'); 

不應該有單引號括起來testList - 要使用的內容該變量,而不是字符串文字「testList」。

0

變量不要作爲一個字符串傳遞:$('#here').html('testList');它傳遞不帶引號:$('#here').html(testList);

0

這裏是最簡單的版本:

$(document).ready(function() { 
    var test = ["text1", "text2", "text3"]; 
    $('#here').html(test.join("<br>")); 
});