1

下面我的客户端代码从服务器获取一些数据,然后将数据呈现到屏幕上。

追加”的作用是将最新数据放在列表末尾,而我希望将最新数据显示在列表顶部。我正在寻找类似append before 或 append at the start 之类的东西。

任何帮助,将不胜感激。

<script>
    for(var i = 0 ; i < data.length; i++){
        $('#uls').append('<li><p>' + data[i].summary + '</p></li>');
    }
</script>

<body>
    <div id="main">
        <ul id="uls"></ul>
    </div>
</body>
4

6 回答 6

2

我想你正在寻找prepend

您的代码将变为:

<script>
    for(var i = 0 ; i < data.length; i++){
        $('#uls').prepend('<li><p>' + data[i].summary + '</p></li>');
    }
</script>

<body>
    <div id="main">
        <ul id="uls"></ul>
    </div>
</body>
于 2012-12-27T08:01:08.763 回答
0

您可以使用将指定内容作为第一个子项插入的方法“prepend”,如下所示:

<script>
    for(var i = 0 ; i < data.length; i++){
        $('#uls').prepend('<li><p>' + data[i].summary + '</p></li>');
    }
</script>

<body>
    <div id="main">
        <ul id="uls"></ul>
    </div>
</body>
于 2012-12-27T08:01:26.890 回答
0

为此使用innerHTML

document.getElementById('uls').innerHTML="<li><p>"+data[i].summary+"</p></li>"+document.getElementById('uls').innerHTML
于 2012-12-27T08:02:22.313 回答
0

您可以通过两种方式执行此操作,.prepend()或者.prependTo()

  1. http://api.jquery.com/prepend/
  2. http://api.jquery.com/prependTo/

拿这些

$('#uls').prepend('<li><p>' + data[i].summary + '</p></li>');
$('<li><p>' + data[i].summary + '</p></li>').prependTo('#uls');
于 2012-12-27T08:17:01.137 回答
0

您实际上并不需要 jQuery:

var ul = document.getElementById('uls'); // Get the ul

var li = document.createElement('li'); // Create a <li>
var p = document.createElement('p'); // Create a <p>

li.appendChild(p); // Add the <p> to the <li>
p.appendChild(document.createTextNode(data[i].summary)); // Add the text to the <p>

ul.insertBefore(li, ul.childNodes[0]); // Add the <li> to the first position of the <ul>.

工作样本

我知道它比 jQuery 选项的代码更多,但它也更快。

于 2012-12-27T08:18:51.783 回答
0

如果你真的需要使用 jQuery,我建议你这样做:

<script>
var i,
    dataMaxIndex,
    ulsContent = "";
dataMaxIndex = data.length - 1;
if (dataMaxIndex >= 0) {
    for (i = dataMaxIndex; i >= 0; i = i - 1) {
        ulsContent = ulsContent + '<li><p>' + data[i].summary + '</p></li>';
    }
    $(document.getElementById('uls')).prepend(ulsContent);
}
</script>

一些代码改进: - 最好使用 document.getELementById 选择器并将其包装为 jQuery - 一次性插入所有 HTML 内容(不是每次迭代);

示例:http: //jsfiddle.net/8RLcx/

于 2012-12-27T08:47:38.193 回答