簡體   English   中英

將關聯數組作為參數傳遞給jTemplates

[英]Passing an associative array to jTemplates as a parameter

我創建了一個jTemplate來顯示“測試”對象的數組。 該數組是一個常規索引數組。 該模板非常基本,僅使用{#foreach}即可遍歷數組中的項目並將其顯示在一個小表中。 這個模板完成了工作,我得到了預期的輸出。

    // Setup the JTemplate. 
    $('#tests_div').setTemplate($('#tests_template').html());

    try {

        // Process the JTemplate to display all currently selected tests.
        $('#tests_div').processTemplate(_selectedTests);
    }
    catch (e) {
        alert('Error with processing template: ' + e.Description);
    }


    <script type="text/html" id="tests_template">
       {#foreach $T as tests}
          <table>
             <tr>
                <td>Index: {$T.tests.index}</td>
                <td>Name: {$T.tests.firstname} {$T.tests.lastname}</td>
                <td>Score: {$T.tests.score} </td>
             </tr>
          </table>
      {#/for}
    </script>

我想做的是將數組更改為關聯數組,並使用測試的索引將對象存儲在其中。 當以后需要對測試進行一些操作時,這使工作變得更容易。

var a = new Test;
a.index = 12345678;
_selectedTests[a.index] = a;

但是,當我將數組傳遞給模板時,出現有關該腳本的錯誤,導致瀏覽器運行緩慢,詢問我是否要停止它。 似乎它處於無盡的循環中。 我不確定模板是否正確讀取數組。 誰能告訴我我如何使用jTemplates中的關聯數組?

您的問題是您的數組認為它是巨大的:

_selectedTests[12345678] = a; // creates an array of 12345678 elements!! length of 12345678

因此您可以執行以下操作:

_selectedTests[a.index.toString()] = a; // creates an associative array with one key "12345678", length of 1

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM