如何将数据从json注入html

u5i3ibmn  于 2021-09-13  发布在  Java
关注(0)|答案(2)|浏览(299)

我正在做一个小项目来读取json文件,并将每个对象插入已经存在的html中的一个div中。因此,如果您检查以下内容,我需要json文件中的id和类按以下顺序显示:

"id": external-events-list "class": fc-event fc-h-event.fc-daygrid-event.fc-daygrid-block-event.fc-event-main

问题是,我不能让它工作到我想要的地方。请检查此js代码:

<script>
    $(document).ready(function () {

        $.getJSON("resources.json", 
                function (data) {
            var employee = '';

            $.each(data, function (key, value) {

                //CONSTRUCTION OF ROWS HAVING
                // DATA FROM JSON OBJECT
                employee += '<tr>';
                employee += '<td>' +  
                value.id + '</td>';  // THe ID is showing up - So like this it works!

                employee +=  '<div class="fc-event-main">' +  '<div class="fc-event.fc-h-event.fc-daygrid-event.fc-daygrid-block-event">' +
                    value.title + '</div>' + '</div>'; //But this Doesn't WORK! 

            });

            //INSERTING ROWS INTO TABLE 
            $('.fc-event-main').append(employee);
        });
    });
</script>

下面是html代码:

<body>
  <div id='wrap'>

    <div id='external-events'>

      <div id='external-events-list'>
        <div class='fc-event fc-h-event fc-daygrid-event fc-daygrid-block-event'>
          <div class='fc-event-main'>Employee 1</div>
        </div>
        <div class='fc-event fc-h-event fc-daygrid-event fc-daygrid-block-event'>
          <div class='fc-event-main'>Employee 2</div>

    </div>

  </div>
</body>
</html>

我正在阅读的json代码如下:

[
    {
        "id": "1",
        "title": "John",
    },
    {
        "id": "2",
        "title": "Tom",
    }
]
tez616oj

tez616oj1#

很难说您到底想要这个脚本做什么,因为您将表单元格与div标记和一个列表混合在一起,每个div都附加一个class标记。有很多小错误。这是我的解释。看一看。注意,我使用了反勾号和模板文字来显示数据。这使得代码更清晰,更易于阅读。

$(document).ready(function() {
  //  $.getJSON("resources.json",
  //   function(data) {
  let data = [{
      "id": "1",
      "title": "John",
    },
    {
      "id": "2",
      "title": "Tom",
    }
  ]
  let employee = '';

  $.each(data, function(key, value) {
    employee += `<div class='fc-event fc-h-event fc-daygrid-event fc-daygrid-block-event'>
        <div class='fc-event-main'>Employee ${key+1}</div>
      <table><tr><td>${value.id}</td>
    <td><div class="fc-event-main">
    <div class="fc-event.fc-h-event.fc-daygrid-event.fc-daygrid-block-event">${value.title}</div>
    </div></td></tr></table>
    </div>`;
  });

  //INSERTING ROWS INTO TABLE 
  $('#external-events-list').append(employee);
  //  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id='wrap'>

  <div id='external-events'>
    <div id='external-events-list'>
    </div>
  </div>
</div>
svmlkihl

svmlkihl2#

如果您想要更健壮、更抽象的东西,您可能会发现这很有趣,可以根据需要应用于样式/类。
如果处理可能要添加和删除的项目,则应处理对象,然后运行渲染函数来渲染项目,如果要向项目添加单击事件,这一点尤其重要。

let employee = (function() {

  let root, form, data = []

  function init(elm, items) {
    root = elm
    data = items

    render()
  }

  function cancel() {
    form.find('[name="title"], [name="id"]').val('')
    form.find('.add').show()
    form.find('.update, .cancel').hide()
  }

  function add(id, title) {
    data.push({
      id: data.length ? parseInt(data[data.length - 1].id, 10) + 1 : 1,
      title: form.find('[name="title"]').val()
    })
    cancel()
    render()
  }

  function edit(item) {
    form.find('[name="id"]').val(item.id)
    form.find('[name="title"]').val(item.title)
    form.find('.add').hide()
    form.find('.update, .cancel').show()
  }

  function update() {
    let id = parseInt(form.find('[name="id"]').val(), 10)
    data.splice(data.findIndex(v => v.id === id), 1, {
      id,
      title: form.find('[name="title"]').val()
    })

    cancel()
    render()
  }

  function remove(item) {
    data.splice(data.indexOf(item), 1)
    render()
  }

  function render() {
    root.empty()

    form = $(`
      <form>
        <input type="hidden" name="id" />
        <input type="text" name="title" />

        <button type="button" class="add">+</button>
        <button type="button" class="update">✔️</button>
        <button type="button" class="cancel">x</button>
      </form>
     `)
    form.find('.add').click(add)
    form.find('.update').hide().click(update)
    form.find('.cancel').hide().click(cancel)

    let list = $('<div id="events-list" />')

    $.each(data, function(key, value) {
      let item = $(`
        <div>
          <div>
            Employee ${parseInt(value.id, 10)} - ${$('<span/>').text(value.title).text()} 
            <button class="delete">X</button> <button class="edit">Edit</button>
          </div>
        </div>
      `)
      item.find('.delete').click(() => remove(value))
      item.find('.edit').click(() => edit(value))

      list.append(item)
    })

    root.append(list)
    root.append(form)
  }

  return {
    init
  }
})()

$(document).ready(function() {
  // $.getJSON("resources.json", function(data) {
  let data = [{
      "id": "1",
      "title": "John",
    },
    {
      "id": "2",
      "title": "Tom",
    }
  ]
  employee.init($('#events'), data || [])
  //})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id='events'></div>

相关问题