Javascript变量范围:无法读取未定义的属性“ id”

时间:2018-12-21 20:43:10

标签: javascript jquery scope var

<script>
        $(document).ready(function(){
            $.ajax({
                dataType: "json",
                url: "scripts/data.php",
                success: function(response) {
                    var data = response;

                    // Works
                    console.log(data[0]['id']);
                    for (i=0;i<data.length;i++) {
                        $.get("card.html", function(html){
                            $('#houses').append(html);

                            // Cannot read property 'id' of undefined
                            $('#houses > div:last-child').addClass(data[i]['id']);
                            $('#houses div:last-child [data="title"]').html(data[i]['nome']);
                            $('#houses div:last-child [data="desc"]').html(data[i]['desc']);
                            $('#houses div:last-child [data="price"]').html(data[i]['preco']);
                        });
                    }
                }
            });
        });
    </script>

我正在创建一个页面,该页面从php页面获取json数据,然后针对每个结果加载一个html页面,然后将其编辑为所需的数据。

这是我第一次创建JavaScript,我不明白为什么我可以使用刚刚在$ .get()之外但不在其中接收到的数据。...只是给出“无法读取未定义的属性'id' ”,并返回未更改的html页面...

有任何线索吗?

0 个答案:

没有答案