javascript - jquery 有更好的循环吗?

标签 javascript jquery coding-style iteration

我正在 javascript 中执行此操作,只是想知道是否可以使用更多 jquery 更优雅地解决它?

var tbl="";
    for(var i=1; i<13; i++) {
        // creating 12 div's, one for each month
        tbl += "<div class='month' id='m"+i+"'>" + months[i-1];

        // creating 31 divs for each day in month
        for(var j=1; j<32; j++) { 
            tbl += "<div class='monthday' id='m"+i+"d"+j+"'>"+
                        "<div class='date_header'>"+j+"</div>" +
                        "<div class='date_info'></div>" +
                   "</div>";
        }
        // close month-div
        tbl += "</div>";

        // insert a clear for each 4th month to get a nice style-break
        if(i==4 || i==8 || i==12) {
            tbl += "<br style='clear: both'>";
        }
    }

    // finished
    $("#friendsinfo").html(tbl);

最佳答案

查找jQuery Templates 。它们允许您做您正在做的事情,而无需像这样在循环中手动连接字符串。这是其工作原理的示例:

var template = '<a href="${link}" id="{$id}">${anchor}</a>';
$.template('myTemplate', template);
var data = [];
for (var x = 0; x < something.length; x++) {
    var newLink = {
        link: something[x].url,
        id: 'mylink-' + something[x].id,
        anchor: something[x].title
    };
    data.push(newLink);
}

$.tmpl('myTemplate', data).appendTo('#myContainer');

我已经在几个项目中使用它们,它们在构建复杂的 HTML block 方面创造了奇迹。

关于javascript - jquery 有更好的循环吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6858480/

相关文章:

javascript - 如果 href 具有有效的 URL,则显示 .load-overlay

jquery - 从检查的输入中获取标签

java - Checkstyle 规则以防止调用某些方法和构造函数

javascript - 相对路径不起作用 RequireJS

javascript - 容器获得不必要的 margin

python - 一个完整的、完整的初学者如何阅读源代码?

c# - 重复的私有(private)成员变量是否优于共享的 protected 成员?

javascript - 在 ember.js 的 Controller 中使用另一个路由模型

javascript - 如何在 Gulp 4 中使用异步/等待?

javascript - jQuery.Validate - 如何将错误结果放在不同的地方?