how to update a list of html items based on a list of json data

微笑、不失礼 提交于 2019-12-11 08:18:35

问题


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>

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

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

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.

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

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, 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);
                }
            }
        });

回答1:


It might be easier to have an outer loop for each checkbox, and an inner loop go through each json element, enabling or disabling based on whether the element/checkboxes have a match.

So an inversion of what you have:

function(data) {
    $('#myList').children('li').each(function() {
        // loop through your data elements here
    });
}

Another option (probably less desirable because it may cause multiple disabled/enabled transitions) is to disable all checkboxes, and enable them as you loop through each element.




回答2:


I have found my problem. rather than doing:

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

        }

I needed to do:

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

        }


来源:https://stackoverflow.com/questions/5400230/how-to-update-a-list-of-html-items-based-on-a-list-of-json-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!