1

現在、私はこのコードを持っています。

  1. URLからjsonを取得します
  2. 最初のレベルでは、学生情報のようにヘッダー列を左側に、データを右側に配置します
  3. Student.subjects のような他のネストされたデータについては、ヘッダー フォーム キーと vals からのデータを含むテーブルを作成します。

    $.getJSON('api/data.json', function(data) {
        var student = [];
        $.each(data, function(key, val) {
        student.push('<tr><td>' +key+'</td><td>' + val + '</td></tr>');
        });
    
    
    
        var subjects = [];
        subject.push('<table><tr>');
    
        $.each(data.subject[0], function (key, val) {
            decision.push('<th>' +key+'</th>');
        });
    
        subject.push('</tr><tr>');
    
        $.each(data.subject, function () {
            mydata = this   
            $.each(mydata, function (key, val) {
                    subject.push('<td>'+val+'</td>');
                });
    
                subject.push('</tr><tr>');
        });
    
        subject.push('</tr></table>');
    
    
        $(student.join('')).appendTo('table#student_table');
        $(subject.join('')).appendTo('table#subject_table');
    
    });
    

data.subjects主題の配列がある場合、その下に新しいテーブル行を追加するように、ハードコーディングではなく自動的に検出する一般的な方法はありますか。

このコードは汚れているように見えます。そのためのより良いアプローチ

4

2 に答える 2

0

JavaScriptに過剰なHTMLタグが混在していることに気付いた場合は、おそらくテンプレートソリューションが必要です。underscore.jsには、_.template()これを解決する関数があります。

javascript

$.getJSON('api/data.json', function(data) {
    var compiled_student = _.template($("template-student-row".html(), {data:data}));
    $("#student_table").append(compiled_student);

    var compiled_subject = _.template($("template-subject-row".html(), {keys: Object.keys(data.subject[0]), subjects: data.subject)}));
    $("#subject_table").append(compiled_subject);

});

html

<script id='template-student-row' type='text/template'>
<% _.each(data, function(k,v){ %>
    <tr>
        <td><%= k %></td>
        <td><%= v %></td>
    </tr>
<% }); %>
</script>

<script id='template-subject-row' type='text/template'>
    <tr>
        <% _.each(keys, function(k){ %> <th><%= k %></th> <% }); %>
    </tr>
    <tr>
        <% _.each(subjects, function(s){ %> <td><%= s %></td> <% }); %>
    </tr>
</script>

<table id='student_table'></table>
<table id='subject_table'></table>
于 2013-02-25T08:56:04.663 に答える
0

マークアップとコードを混在させるのは好きではありません。データのレンダリングにはテンプレート エンジンを使用することをお勧めします。他にもたくさんありますが、一般的なテンプレート エンジンの 1 つにjQuery templateがあります。

それを質問に適用するには、次のようにします。

var studentRow = "<tr><td>${key}</td><td>${val}</td></tr>";

// Compile the markup as a named template
$.template("studentTable", studentRow);

$.getJSON('api/data.json', function(data) {
    $.tmpl("studentTable", data).appendTo("table#student_table");
}

#student_tableただし、テーブルの先頭と末尾を含めるには、マークアップを変更する必要があります。

于 2013-02-25T08:20:12.910 に答える