【问题标题】:Loop through array and match items to html elements循环遍历数组并将项目与 html 元素匹配
【发布时间】:2013-03-07 17:31:25
【问题描述】:

我正在寻找一种更直观的方式来运行下面的代码(因为它也不符合我的目的)。

for (j = 0; j<items.length; j++) {
            var indivItem = items[j];
               if (indivItem.category == 1) {
                  $('.indiv_category[idnumber="1"]').append('<ul class="left_side_item"><li>'+indivItem.title+'</li></ul>');
               }
               else if (indivItem.category == 2) {
                  $('.indiv_category[idnumber="2"]').append('<ul class="left_side_item"><li>'+indivItem.title+'</li></ul>');
               }
            }

基本上我需要第 3 行检查 if (indivItem.category &gt; 0) 然后查找具有匹配 idnumber 属性的元素并附加必要的信息。

对于可用的.indiv_category 元素的长度,我需要这个继续。

基本上,将“项目”array 中的所有项目与具有匹配“idnumber”属性的所有元素匹配到数组中包含相同 ID 号的项目。

【问题讨论】:

    标签: javascript jquery arrays loops


    【解决方案1】:

    删除条件,只在选择器中使用变量items[j].category

    for (j = 0; j<items.length; j++) {             
        $('.indiv_category[idnumber="'+ items[j].category + '"]').append('<ul class="left_side_item"><li>'+indivItem.title+'</li></ul>');             
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-09
      • 1970-01-01
      相关资源
      最近更新 更多