如何使用rv-each构建动态HTML

时间:2015-06-03 06:57:06

标签: javascript html5 dynamic rivets.js

我有两个阵列卡车和工作。现在我必须使用这两个数组构建一个列表。它就像循环两个for循环。对于第一个数组(卡车)中的每个元素(id),我需要仅使用相应的作业ID循环遍历第二个数组(作业)。

例如: id:1 - 应该包含 - thing1,thing2,thing3,thing4 id:2 - 应该包含 - thing5,thing6,thing7,thing8

我需要使用rv-each或者铆钉为上面的列表构建动态html。

这是我的小提琴:http://jsfiddle.net/keshav_1007/wa5osfec/3/

HTML:

<div id="contentWrap">
    <ol rv-each="truck" rv-value="truck.id">
        <li rv-each-job="jobs" rv-value="job.id">{ job.job_number }</li>
    </ol>
</div>

JS:

    $(document).ready(function(){
    window.view = rivets.bind($('#contentWrap'),{
        truck:[{id:1},
               {id:2},
               {id:3},
               ],
        jobs:[
            {id:1,job_number:'thing1'},
            {id:1,job_number:'thing2'},
            {id:1,job_number:'thing3'},
            {id:1,job_number:'thing4'},
            {id:2,job_number:'thing5'},
            {id:2,job_number:'thing6'},
            {id:2,job_number:'thing7'},
            {id:2,job_number:'thing8'},
        ]
    });
});

现在我收到了数组中的所有项目。但是我需要获得与第一个数组相关的元素,就像我在“例如”中提到的那样。

帮我解决这个问题。我试过了,但我无法让它发挥作用。

提前感谢。

1 个答案:

答案 0 :(得分:1)

看看这个:http://rivetsjs.com/docs/guide/#formatters

我创建(更新)了你的小提琴:http://jsfiddle.net/wa5osfec/7/

<强> HTML:

使用formatter将返回值修改为rv-each- *。当然,你也可以传递你想要比较的价值(在这种情况下你的身份)。

<li rv-each-job="jobs | compare truck.id" rv-value="job.id">{ job.job_number }</li>

<强> JS:

(小心.forEach并没有经过深思熟虑。考虑到它不会在更大的数组和重复上表现出来)

rivets.formatters.compare = function(array, compare) {

    var tempArr = [];

    array.forEach(function(element, index, array) {
        if (element.id == compare) {
            tempArr.push(element);
        }
    });

    console.log(tempArr);

    return tempArr;
}