在jQuery模板中仅显示前10个。

3
我们正在使用jQuery、jQuery模板和Wufoo jQuery API来显示我们表单中的数据,以下是代码:

我们使用以下代码:

<div id="people">           
    <ul>
        <script id="attendeeTemplate" type="text/x-jquery-tmpl">
            <li>
                <h4>${Field1}</h4>
                ${Field3} minutes
            </li>
             </script>
    </ul>
</div>

这个很好用,但我们想限制它仅显示前10个条目。现在它正在显示数据库中的每个条目(使用下面的JavaScript和API排序)。请注意,我们只想显示前10个,按分钟数从高到低排序。
以下是JavaScript内容:
<script>
    function processEntries(data) {
        $.each(data.Entries, function(entriesIndex, entriesObject) {
            // Make sure this entry has all the required bits
            if (entriesObject.Field1 && entriesObject.Field3) {
                $("#attendeeTemplate").tmpl(entriesObject).appendTo("#people ul");  
            }
        });
    };

    $.wufooAPI.getEntries({
        "callback"   : processEntries,             // Name of custom function declared above
        "formHash"   : "BLAH",                   // Found by clicking "Code" button from the Form Manager, then the "API Information" button
        "sortID"   : "Field3",                   // Found by clicking "Code" button from the Form Manager, then the "API Information" button
        "sortDirection"   : "DESC",                   // Found by clicking "Code" button from the Form Manager, then the "API Information" button

    });
</script>

任何有关如何将其限制在前10名的想法都将非常有帮助!
3个回答

3
这应该可以运行:
data.Entries.slice(0,9); 

2
如果您无法使用数据库来限制,仍然可以像这样进行修复:
function processEntries(data) {
    var i = 0;
    $.each(data.Entries, function(entriesIndex, entriesObject) {
        // Make sure this entry has all the required bits
        if (entriesObject.Field1 && entriesObject.Field3 && i<10) {
            $("#attendeeTemplate").tmpl(entriesObject).appendTo("#people ul");
            i++;
        }
    });
};

注意:假设您之前已经以某种方式排序了条目。

@MoritzPetersen 的解决方案更好,我不知道 slice,我的代码在第十个条目之后仍然会添加一个循环。 - Ricardo Garza V.

1
假设 data.Entries 是一个数组,您可以使用 Array.slice()
$.each(data.Entries.slice(0, 9), function(entriesIndex, entriesObject) {

工作得非常好,就像这里所有其他快速答案一样。谢谢! - Nietzsche

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接