【问题标题】:Filter Json object attribute to add css style过滤Json对象属性添加css样式
【发布时间】:2012-10-22 13:26:07
【问题描述】:

感谢您的帮助,学习如何做到这一点,假设我有一个类似于这个的代码。

主干脚本:

$(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"
  }
]

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

就像这个:

<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>

【问题讨论】:

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


    【解决方案1】:

    你有你需要的一切,只需使用模板:

    <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)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-07-24
      • 2015-09-21
      • 2013-12-18
      • 2018-07-27
      • 2021-10-03
      • 1970-01-01
      • 2023-04-09
      • 2021-10-23
      相关资源
      最近更新 更多