2012-08-08 45 views
0

我寫一個簡單的函數,將更新數據的第N頁的最新值的列表,從服務器推。爲了簡單起見,我使用計時器來模擬服務器推送。的jQuery:動態更新

每次服務器消息推,我想更新顯示在頁面上,與放置在列表頂部新接收的消息列表,並最早被丟棄的名單。

這是我到目前爲止有:

<html> 
    <head> 
     <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script> 
    </head> 
    <body> 
     <div id="main_cntr"> 
      <ul id="lst"> 
       <li>Line 1 ....</li> 
       <li>Line 2 ....</li> 
       <li>Line 3 ....</li> 
       <li>Line 4 ....</li> 
       <li>Line 5 ....</li> 
      </ul> 
     <div> 
    </body> 
    <script type="text/javascript"> 
     // mimics server side push message received at front end 
     // update list to contain only the last 5 elements 
     function update_list(newtext){ 
      // Fetch li elements in $('#lst') 
      // truncate last one 
      // insert new text to top of li list (ideally, I want to pass the new text to insert to this function) 
      alert('Got called') 
     } 

     $(document).ready(function() { 
      window.setInterval(update_list, 10000); 
     }); 
    </script> 
</html> 

我有2個問題:

  1. 我如何正確地實現這一點(我不是一個真正的JQuery的專家)
  2. 如何我修改功能update_list(),這樣我可以傳遞一個新的文本(例如隨機文本),從而使服務器推它更好地模擬數據?

回答

2

這是基於你的代碼基本例子刪除列表中的最後一個元素,並增加了一個新的列表

// mimics server side push message received at front end 
// update list to contain only the last 5 elements 
function update_list(newtext){ 
    // Fetch li elements in $('#lst') 
    // truncate last one 
    $('#lst li').last().remove() 

    // insert new text to top of li list (ideally, I want to pass the new text to insert to this function) 
    $('#lst').prepend("<li>"+newtext+"</li>"); 

    alert('Got called') 
} 

而且這個頂,如果你想提高你的仿真隨機數據,你可以做這樣的事情

var wordArray = ["hey", "you", "there"]; 

function RandomWord() { 
    var i = Math.floor((Math.random() * wordArray.length)); 
    return wordArray[i]; 
} 

,然後更換線update_list是這個

$('#lst').prepend("<li>"+RandomWord()+"</li>"); 

最後這裏是表示該工作

+1

難道你不想抓住List的孩子嗎?例如$('#lst')。children()。last()。remove()。end()。end()。prepend(「

  • 」+ RandomWord +「
  • 」); – Nimnam1 2012-08-08 15:57:01

    0

    隨機方面的jsFiddle所以,它聽起來像你需要在jQuery的一點101。互聯網是充滿了資源,您看到這篇文章後,我希望你去,並通過對$功率一些教程運行,但現在,我們可以在這方面幫助。

    一個最基本的(普通)的使用jQuery的是讓DOM元素,而無需使用冗長document.getElementById("id")。使用jQuery,我們可以簡單地說$("#id")(注:英鎊符號讓jQuery的知道它找一個對象ID,這很重要)。無論getElementById$回報對象,但如果getElementById返回一個DOM元素,$返回一個jQuery對象。在這種情況下,我們有興趣使用jQuery函數prepend(),具有類似功能的DOM元素的xHTML的附加功能(支持XHTML的外面是janky最好)只有當追加增加它的參數作爲最後一個子功能,在前面加上加他們作爲第一。

    $().prepend()是超級好用。它在它的父對象中的任何現有內容之後添加它的參數。所述參數可以是DOM元素,一個jQuery對象,或一個字符串(任何字符串)。在這種情況下,一個字符串將會很好。

    function update_list(newtext) 
    { 
        $("#lst").prepend("<li>" + newtext + "</li>"); 
    } 
    

    此代碼將創建一個新的jQuery對象,表示你的<ul> ID爲lst(記住:英鎊符號!),並要求它前面加上一個新<li>到它newtext,因爲它的內容。