如何使用for循环而不是$ .each

时间:2014-11-10 22:48:38

标签: jquery json for-loop

这应该是一个简单的,我只是找不到搜索的答案。 我有一个图像库,有大约400个图像,可以在不同的数据上进行过滤。 我使用jquery来读取JSON数据。它循环通过数据来创建图像和标题。 一切正常但它过滤非常缓慢。我读过的所有内容都说使用for循环代替$ .each来加速循环。 问题是我之前没有使用for循环,并且似乎无法使代码正确(我显然不是jquery专家)。这是我正在使用的代码,使用$ .each - 如何用forLoop替换它?

var data = [
{"id":7,"width":54,"colorNumber":91380,"collection":"Adelle","colorName":"Agate","colorRange":"Green/teal","content":"material content goes here","repeat":"repeat","category":"category","origin":"origin"},
{"id":45,"width":54,"colorNumber":91381,"collection":"Adelle","colorName":"Emerald","colorRange":"yellow/gold/orange/red","content":"material content goes here","repeat":"repeat","category":"category","origin":"origin"},
{"id":13,"width":54,"colorNumber":93022,"collection":"Adromeda","colorName":"Galaxy","colorRange":"white/cream","content":"material content goes here","repeat":"repeat","category":"category","origin":"origin"}

......等

];
$.each(data, function(i, obj) {
    $('#images').append(
"<li data-id='" + obj.colorNumber + "' data-type='" + obj.colorRange + "' id='image" + obj.colorNumber +"'>"
+
....etc

1 个答案:

答案 0 :(得分:0)

<强> HTML

<img id='image' src='https://jquery.org/resources/members/wordpress.png'/> 

<强> JS

<script type='text/javascript'>//<![CDATA[ 
$(function(){
var data = [
    {
        "id":7,
        "width":54,
        "colorNumber":91380,
        "collection":"Adelle",
        "colorName":"Agate",
        "colorRange":"Green/teal",
        "content":"material content goes here",
        "repeat":"repeat",
        "category":"category",
        "origin":"origin"
    },
    {"id":45,"width":54,"colorNumber":91381,"collection":"Adelle","colorName":"Emerald","colorRange":"yellow/gold/orange/red","content":    "material content goes here","repeat":"repeat","category":"category","origin":"origin"},
    {"id":13,"width":54,"colorNumber":93022,"collection":"Adromeda","colorName":"Galaxy","colorRange":"white/cream","content":"material content goes here","repeat":"repeat","category":"category","origin":"origin"}];

var html = '<br/><ul>';
for (var i = 0; i < data.length; i++) {
  html += "<li data-id='" + data[i].colorNumber + "' data-type='" + data[i].colorRange + "' id='image" + data[i].colorNumber +"'>" + data[i].colorName + '</li>';
}
$('#image').after(html+'</ul>');
});//]]> 
</script>

<强> FIDDLE