如何更新基于json数据列表的html项目列表 [英] how to update a list of html items based on a list of json data

查看:384
本文介绍了如何更新基于json数据列表的html项目列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的html页面中有一个复选框列表,例如:

I have a list of checkboxes in my html page, like so:

<ul id="myList">
  <li class="checkboxItem">
    <input type="checkbox" name="item1" value="001" id="item-1"/> 
    <label for="item-1" class="checkboxLabel">Display 1</label>
  </li>
  <li class="checkboxItem">
    <input type="checkbox" name="item2" value="042" id="item-2"/>
    <label for="item-2" class="checkboxLabel">Display 42</label>
  </li> 
</ul>

现在我打电话获取一些json数据,如下:

now I make a call to get some json data, which comes back like so:

[{"name":"002","title":"Display 1"}]

我想要做的是循环返回的json并更新复选框列表,以便任何不在返回列表中的项被禁用,

what I want to do is loop the returned json and update the list of checkboxes such that any item not in the returned list is disabled, and those where the title matches a given label, the input value is updated.

因此,在此示例中,item2将被禁用,item1的值将更新为002.

so in this example, item2 will be disables and item1 will have its value updates to 002.

这里是我到目前为止,我不太确定从哪里去,也就是说,在循环内做什么。我确实有一些控制json如何返回,所以如果有意义的retunr json的另一种格式,我可以这样做。

here's what I have so far, i'm not quite sure where to go from here, that is, what to do inside the loop. I do have some control over how the json is returned, so if it makes sense to retunr the json in another format, I can do that.

EDIT,更新函数, 见下文。然而,一旦我在每个函数内部的for循环,elem得到一个值0,而不是一个js对象,如:
{name:002,title:Display 1}。明确的数据,正在从函数的外部范围转移到每个函数的内部范围,但是如何使这种情况发生?

EDIT, updated the function, see below. however, once I get inside the for loop inside the each function, elem is getting a value of "0" rather than a js object such as: {"name":"002","title":"Display 1"}. clearly data, is being transferred from the outside scope of the function to the inside scope of the each function, but how do I make that happen?

function(data) {
        $('#myList').children('li').each(function(i,e) {
            for(var elem in data) {
                var elemDescr = elem['title'];
                var elemName = elem['name'];
                if(elemDescr==$(this).find('.checkboxLabel').text()) {
                    $(this).find('input').attr('value',elemName);
                }
            }
        });


推荐答案

而不是执行:

for(var elem in data) {
            var elemDescr = elem['title'];
            var elemName = elem['name'];

        }

我需要:

for(var index in data) {
            var elemDescr = data[index].title;
            var elemName = data[index].name;

        }

这篇关于如何更新基于json数据列表的html项目列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆