2010-11-10 18 views
1

嗨, 我的數組打印出來的頁面上的值時:爲什麼javascript「write()函數」在jQuery中引用元素時不起作用?

document.write(unsorted[i]+"<br/>"); 

,但不是在試圖把它放在一個div的jQuery

$("#no1").write(unsorted[i]+"<br/>"); 

這裏所指的元素是我的代碼:

$(function(){ 
    var unsorted = new Array(); 
    function randomNumber(x,y) { //gives a random number 
     return Math.floor((Math.abs(y - x) + 1) * Math.random()) + Math.min(x, y); 
    } 

    for(i=0; i<=33; i++){ 
     unsorted[i]=randomNumber(0,33);  //populates the array with random numbers 
     $("#no1").write(unsorted[i]+"<br/>"); //#no1 is a div 
    } 
}); 

無論是我的代碼,jquery庫都經過測試,工作正常! 任何建議爲什麼我的做法是錯誤的感謝所有幫助 10X

回答

4

您只能使用document.write方法時加載頁面時,你不能寫元素已經存在。

把內容一起,並使用html方法jQuery庫擺在div的內容:

var s = []; 
for(i = 0; i <= 33; i++){ 
    unsorted[i] = randomNumber(0, 33); 
    s.push(unsorted[i]); 
} 
$("#no1").html(s.join("<br/>")); 
0

而不是.write()嘗試

$("#no1").html($("#no1").html() + unsorted[i]+"<br/>"); 
+3

不要通過讀寫'html()'來追加。這迫使瀏覽器序列化,銷燬並重新解析DOM內容,這很慢並且丟失了不可序列化的內容,如事件處理程序。改用'append()'。 – bobince 2010-11-10 13:28:37

1

使用html()方法:

$("#no1").html($("#no1").html() + unsorted[i]+"<br/>"); 

設置HTML匹配元素集合中的每個元素 的內容。

+1

使用回調簽名會更好:'$('#no1')。html(function(idx,oldHtml){return oldHtml + unsorted [i] +'
';});'提供了jQuery 1.4。 – lonesomeday 2010-11-10 13:12:05

+0

@lonesomeday:正確地說,除非jquery 1.4在那裏。雖然你的評論在這裏很有用:) – Sarfraz 2010-11-10 13:16:15

1

首先,jQuery函數$('selector')不返回文檔對象,它返回一個jQuery對象,所以追加.write它是行不通的,因爲jQuery對象不包括write方法。這跟說document.write不一樣。

其次,你不會爲此使用document.write; document.write只能在頁面加載之前調用,所以它不能與JQuery一起使用(由於瀏覽器中文件的加載順序,只能在頁面加載後才能使用它)。

JQuery確實提供了各種功能,您可以改用它們。其他人已經建議使用.html()來更改您的<div>的內容。

這是一個很好的建議。但坦率地說,你甚至不需要jQuery。既然你直接引用一個元素有ID,你可以簡單地使用標準的JavaScript和DOM方法getElementById()和innerHTML的

document.getElementById('no1').innerHTML += unsorted[i]+"<br/>"; 

jQuery的選擇將只需要在這種情況下,如果你想要做一個更復雜的選擇器(例如,按類或一次選擇多個元素等),但對於簡單的基於ID的選擇,標準的JavaScript可以很好地完成這項工作。

相關問題