过滤Json对象属性以添加css样式

时间:2012-10-22 13:26:08

标签: php javascript json backbone.js underscore.js

您的帮助很高兴了解如何做到这一点,让我说我有一个类似于这个的代码。

骨干脚本:

$(function(){
  var Band = Backbone.Model.extend();
    var BandList = Backbone.Collection.extend({
    model: Band,
    url: 'feed1.json'
  });

  var BandsView = Backbone.View.extend({
    template: _.template($('#bandlist_template').html()),
    render: function(eventName) {
      _.each(this.model.models, function(band){
        var lTemplate = this.template(band.toJSON());

        $(this.el).append(lTemplate);
      }, this);
      return this;
    }
  });

  var lBands = new BandList;

  var AppView = Backbone.View.extend({
    el: "body",

    render: function(){
      var lBandsView = new BandsView({model:lBands});
      var lHtml = lBandsView.render().el;
      $('#bands').html(lHtml);
    },

    initialize: function(){
      var lOptions = {};
      lOptions.success = this.render;
      lBands.fetch(lOptions);
    }
  });

  var App = new AppView;
});

下划线js模板:

<script type="text/template" id="bandlist_template">
  <?php echo "hello"; ?><li><%= band_name %> - <%= section %></li>
</script>

HTML:

<ul id="bands">
</ul>

JSON:

[
  {
    "id": "149",
    "band_name": "Armthorpe Elmfield",
    "section": "Fourth"
  },
  {
    "id": "127",
    "band_name": "Barnsley Chronicle",
    "section": "Second"
  },
  {
    "id": "155",
    "band_name": "Barnsley Metropolitan Band",
    "section": "Fourth"
  }
]

确定。假设我想根据css json属性更改section样式(只需要将div和样式设为json section属性为'Fourth')。因此,如何过滤该属性并将其推送到同一div内填充ul的另一个主干js。

就像这样:

<ul id="bands">
</li>Armthorpe Elmfield - <div class="styled">Fourth</div><li>
</li>Barnsley Chronicle - Second<li>
</li>Barnsley Metropolitan Band - <div class="styled">Fourth</div><li>
</ul>

1 个答案:

答案 0 :(得分:0)

您拥有所需的一切,只需使用模板:

<script type="text/template" id="bandlist_template">
    <?php echo "hello"; ?>
    <li><%= band_name %> - 
        <% if section is 'Fourth': %>
            <div class="styled">Fourth</div>
        <% else: %>
            <%= section %>
        <% end %>
    </li>
</script>

当然可以做得更好但只是为了证明if和其他控制结构在模板中没有问题。 (在示例中,我在if中使用eco语法,只需修复它以便在需要时使用普通的javascript。)