jQuery:动态更新N个最新值的列表

我正在编写一个简单的函数,它将使用从服务器推送的数据更新页面。 为简单起见,我使用计时器来模拟服务器推送。

每次按下服务器消息时,我想更新页面上显示的列表,新接收的消息放在列表的顶部,最早的消息被删除。

这是我到目前为止:

     
  • Line 1 ....
  • Line 2 ....
  • Line 3 ....
  • Line 4 ....
  • Line 5 ....
// 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); });

我有两个问题:

  1. 我该如何正确实现(我不是一个真正的JQuery专家)
  2. 如何修改函数update_list()以便我可以传递一个新文本(例如随机文本),以便更好地模仿服务器推送的数据?

这是一个基于您的代码的基本示例,它删除列表中的最后一个元素,并在列表顶部添加一个新元素

 // 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("
  • "+newtext+"
  • "); alert('Got called') }

    除此之外,如果你想用随机数据改进你的模拟,你可以做这样的事情

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

    然后将update_list的行替换为this

     $('#lst').prepend("
  • "+RandomWord()+"
  • ");

    最后这里有一个jsFiddle显示了这个工作的随机方面

    所以,听起来你需要在jQuery中使用101。 互联网充满了资源,在你阅读这篇文章之后,我希望你去看看有关$的力量的一些教程,但是现在,我们可以帮助解决这个问题。

    jQuery最基本(也是常见)的用途之一是获取DOM元素而不必使用冗长的document.getElementById("id") 。 使用jQuery我们可以简单地说$("#id") (注意:英镑符号让jQuery知道它正在寻找一个对象ID,这很重要)。 getElementById$返回对象,但是getElementById返回一个DOM元素, $返回一个jQuery对象。 在这种情况下,我们感兴趣的是使用jQuery函数prepend() ,这个函数与DOM元素中的xHTML附加函数具有相似的function(xHTML以外的支持最好是janky),只有在append将它的参数添加为最后一个子元素的情况下, prepend将它们添加为第一个。

    $().prepend()非常容易使用。 它在它的父对象中的任何现有内容之后添加它的参数。 参数可以是DOM元素,jQuery对象或字符串(任何字符串)。 在这种情况下,一个字符串就可以了。

     function update_list(newtext) { $("#lst").prepend("
  • " + newtext + "
  • "); }

    这段代码将创建一个新的jQuery对象,代表你的

      ,id为lst (记住:pound符号!),并要求它使用newtext作为内容在它上面添加一个新的