简体   繁体   English

使用JS在DOM中添加元素

[英]Add elements in the DOM with JS

I'm trying to print in the HTML the data from another part of the site, the data appears on the console, however not in the HTML. 我正在尝试以HTML格式打印网站另一部分中的数据,该数据显示在控制台上,但不在HTML中。

I believe it is an error in the code, could someone point me or direct me? 我认为这是代码中的错误,有人可以指出我还是指导我?

$.ajax({
    type: "GET",
    url: 'https://example.com',
    crossDomain: true,
    success: function (json) {
        var reservas = json;

        reservas.forEach(function (reserva) {
            $(".reservas").append($("<td/>", {
                html: reserva
            }));

            console.log(reserva);
        });
    },
    error: function (e) {
        console.log(e);
    }
});

If i change the variable reservas for: 如果我将变量reservas更改为:

var reservas = ["test", "test2", "test3"]

And the elements are being added.. 和元素正在添加..

when I give console.log (reserve) , the console return: 当我提供console.log (reserve) ,控制台返回:

Object {
  _id: "10152686662737642",
  nome: "First Person",
  email: "email1@gmail.com",
  __v: 0
}(index):68
Object {
  _id: "10152433045473800",
  nome: "Second Person",
  email: "email2@gmail.com",
  __v: 0
} (index):68

maybe the problem is that is not an array? 也许问题在于那不是数组吗?

Based on your clarifications. 根据您的说明。 I believe what you want to do is: 我相信您想做的是:

$(".reservas").append($("<td/>", {
    html: JSON.stringify(reserva)
}));

either that or $(".reservas") isn't finding any elements in the DOM. 或$(“。reservas”)在DOM中找不到任何元素。 Also you may want to do something like: 另外,您可能想要执行以下操作:

$(".reservas").append($("<td/>", {
    html: reserva.nome + "  " + reserva.email
}));

instead depending on what you actually want to display 而是取决于您实际要显示的内容

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM