在阅读JSON文件后如何操作HTML?

时间:2016-02-03 16:59:50

标签: javascript jquery json

create table TABLEA (ID int);

insert into TABLEA (ID) values (1);
insert into TABLEA (ID) values (2);
insert into TABLEA (ID) values (3);
insert into TABLEA (ID) values (4);
insert into TABLEA (ID) values (5);

create table TABLEB (ID int, code int);

insert into TABLEB (ID,code) values (1,0);
insert into TABLEB (ID,code) values (2,0);
insert into TABLEB (ID,code) values (3,0);
insert into TABLEB (ID,code) values (4,0);
insert into TABLEB (ID,code) values (5,0);
insert into TABLEB (ID,code) values (6,0);
insert into TABLEB (ID,code) values (7,0);
insert into TABLEB (ID,code) values (8,0);

UPDATE TABLEB SET CODE=1 FROM TABLEB B INNER JOIN TABLEA as A on A.id=B.id;

SELECT * FROM TABLEB;

ID  CODE
1   1
2   1
3   1
4   1
5   1
6   0
7   0
8   0

我知道json是我的JSON对象。我想用它来操纵我的HTML

如果它是我的JSON对象中的第一项,那么

<script type="text/javascript">
    window.alert = function(){};
    var defaultCSS = document.getElementById('bootstrap-css');
    function changeCSS(css){
        if(css) $('head > link').filter(':first').replaceWith('<link rel="stylesheet" href="'+ css +'" type="text/css" />'); 
        else $('head > link').filter(':first').replaceWith(defaultCSS); 
    }
    $( document ).ready(function() {
      $.getJSON("./data/data.json", function(json) {
        console.log(json.length); // this will show the info it in firebug console
      });
    });
</script>

我想重复上面的代码n次

1 个答案:

答案 0 :(得分:1)

有很多方法可以做到这一点,但最简单的方法可能是构建一个字符串并将其附加到你希望它存在的任何容器中。

$.getJSON("./data/data.json", function(json) {
  $.each(json, function(data) {
    var html = '<p>' + data.quote + '</p>' +
               '<small>' + data.person + '</small>';

    $('#MySuperSpecialDiv').append(html);
  });
});

请注意,这不会很好地扩展。如果你要添加比现有更多的标记,你应该考虑某种模板替代方案。

另外,如果有人支持你维护这个项目,你可能不会成为他们最喜欢的人。