backbone.js 如何为模板元素添加不同的类?

wlsrxk51  于 2022-11-10  发布在  其他
关注(0)|答案(2)|浏览(199)

在我的JSON文件中,我有7个对象,其中前3个有"is_read" attribute == 1,,后4个有"is_read" == 0。我使用模板添加行,并希望根据它们的"is_read"值为tr提供不同的类(".news_read"对应"is_read" == 1".news_unread"对应"is_read" == 0)。
然而,我最终得到了7行,它们都有“news_unread”类,尽管console.log显示我有3个"newsData.get('is_read') == 1"和4个"newsData.get('is_read') == 0"对象。
我想知道如何创建具有不同类的行。我尝试执行newsRow.addClass,但错误消息指出对象<tr><td>...</td></tr>(newsRow模板)不能有方法addClass。

render: function() {
    news.fetchMyNews();
    for (var i = 1; i <= news.length; i++)   {
        var newsData = news.get(i);
        var newsRow = JST["news/row"](newsData.attributes);
        $("#news_tbody").append(newsRow).first('tr').attr("class",function(){
            if (newsData.get('is_read') == 1)
                return "news_read";
            else if (newsData.get('is_read') == 0)
                return "news_unread";
        });
    }           
}
ogsagwnx

ogsagwnx1#

您写道:
我试着做newsRow.addClass,但是错误消息说对象...(newsRow模板)不能有方法addClass。
但在示例代码中找不到addClass

$("#news_tbody").append(newsRow).first('tr').attr("class",function(){
    if (newsData.get('is_read') == 1)
        return "news_read";
    else if (newsData.get('is_read') == 0)
        return "news_unread";
 });

我只是建议您尝试以下代码(使用addClass,而不是attr,并在if语句中添加块):

$("#news_tbody").append(newsRow).first('tr').addClass(function(){
    if (newsData.get('is_read') === 1){
        return "news_read";
    } else if (newsData.get('is_read') === 0) {
        return "news_unread";
    }
});
m528fe3b

m528fe3b2#

正如@Pinal建议的那样,我使用了addClass。
然而,在append(newsRow)之后,我使用了.children('tr'),它工作得很好。

$("#news_tbody").append(newsRow).children('tr').addClass(function(){
  if (newsData.get('is_read') === 1){
    return "news_read";
  } else if (newsData.get('is_read') === 0) {
    return "news_unread";
  }
});

相关问题