-1

私はdivにjsonを入力していますが、最善の方法ではないと思います。たくさんのコードのようで、共有できるように見えるものもあります。

//data for DOM
$.getJSON('json/device.json', function (data) {
    var items = [];
    $.each(data[0].attributes, function (key, val) {
        items.push('<li id="' + key + '">' + '  ' + val + '</li>');
    });

    $('<ol/>', {
        'class': 'raw-list',
        html: items.join('')
    }).hide().fadeIn().appendTo('.json');
});

$.getJSON('json/device.json', function (data) {
    var items = [];
    $.each(data[0].status, function (key, val) {
        items.push(val);
    });

    $('<span/>', {
        'class': 'sort-label error',
        html: items.join('')
    }).hide().fadeIn().appendTo('.status-input .sort-label');
});

$.getJSON('json/device.json', function (data) {
    var items = [];
    $.each(data[0].location, function (key, val) {
        items.push(val);
    });

    $('<span/>', {
        'class': 'sort-label',
        html: items.join('')
    }).hide().fadeIn().appendTo('.location-input .sort-label');
});

$.getJSON('json/device.json', function (data) {
    var items = [];
    $.each(data[0].type, function (key, val) {
        items.push(val);
    });

    $('<span/>', {
        'class': 'sort-label',
        html: items.join('')
    }).hide().fadeIn().appendTo('.type-input .sort-label');
});

$.getJSON('json/device.json', function (data) {
    var items = [];
    $.each(data[0].brand, function (key, val) {
        items.push(val);
    });

    $('<span/>', {
        'class': 'sort-label',
        html: items.join('')
    }).hide().fadeIn().appendTo('.brand-input .sort-label');
});
4

1 に答える 1

3

$.getJSON毎回同じデータを取得する場合は、複数回呼び出す必要はありません。

例えば:

$.getJSON('json/device.json', function(data) {

  // First set of display logic
  var items = [];
  $.each(data[0].attributes, function (key, val) {
     items.push('<li id="' + key + '">' + '  ' + val + '</li>');
  });

  $('<ol/>', {
    'class': 'raw-list',
    html: items.join('')
  })
  .hide().fadeIn().appendTo('.json');

  // Second set of display logic
  var items = [];
  $.each(data[0].status, function (key, val) {
    items.push(val);
  });

  $('<span/>', {
    'class': 'sort-label error',
    html: items.join('')
  })
  .hide().fadeIn().appendTo('.status-input .sort-label');

});

ほとんどのデータセットの表示ロジックに同様のコードブロックを使用しているため、これを関数にラップできます。

function displaySortLabel(items, parentClass) {
  $('<span/>', {
    'class': 'sort-label',
    html: items.join('')
  }).hide().fadeIn().appendTo('.' + parentClass +' .sort-label');
}

そしてそれを次のように呼びます:

displaySortLabel(items, "location-input");
于 2013-02-13T21:33:07.723 に答える