gpt4 book ai didi

javascript - 如何将多个元素附加到一个div?

转载 作者:行者123 更新时间:2023-11-30 20:32:32 25 4
gpt4 key购买 nike

因此,我正在访问一个待办事项列表 API 来制作一个非常基本的待办事项列表应用程序。我能够显示我从 api 调用的内容,我将标题、描述和价格分别附加到 h1、h3 和 h4,然后在用户填写表单时将其显示到文档中。

我如何将这三个附加到一个 div 中,以便我可以将 CSS 应用于每个单独的待办事项,或者以便我可以在我想删除或编辑待办事项时添加一个按钮?

如果可能的话,我想用普通的 JavaScript 来做这件事。

这是我的 JavaScript 代码,如果您在现有代码中看到任何您认为可以改进或更改的地方,或者如果我做错了什么,请告诉我。我在这方面还是一个初学者,所以我可以使用我能得到的所有帮助。

function Todo(title, description, price){
this.title = title;
this.description = description;
this.price = price;
}

document.todo.addEventListener("submit", function(e){
e.preventDefault();

var titleForm = document.todo.title.value;
var descriptionForm = document.todo.description.value;
var priceForm = document.todo.price.value;

var newTodo = new Todo(titleForm, descriptionForm, priceForm);

axios.post("<todo api url>", newTodo).then(function(response){
console.log(response.data);
})
})

axios.get("<todo api url>").then(function(response){
for(var i = 0; i < response.data.length; i++){
var h1 = document.createElement("h1");
var h3 = document.createElement("h3");
var h4 = document.createElement("h4");

var displaytitle = document.createTextNode(response.data[i].title);
var displayDescription = document.createTextNode(response.data[i].description);
var displayPrice = document.createTextNode(response.data[i].price);

h1.appendChild(displaytitle);
h3.appendChild(displayDescription);
h4.appendChild(displayPrice);

document.body.appendChild(h1);
document.body.appendChild(h3);
document.body.appendChild(h4);
}
})

最佳答案

不是将它们附加到 document.body,而是创建一个 DIV 并将它们附加到 DIV,然后将 DIV 附加到正文。

axios.get("<todo api url>").then(function(response){
for(var i = 0; i < response.data.length; i++){
var h1 = document.createElement("h1");
var h3 = document.createElement("h3");
var h4 = document.createElement("h4");
var div = document.createElement("div");

var displaytitle = document.createTextNode(response.data[i].title);
var displayDescription = document.createTextNode(response.data[i].description);
var displayPrice = document.createTextNode(response.data[i].price);

h1.appendChild(displaytitle);
h3.appendChild(displayDescription);
h4.appendChild(displayPrice);

div.appendChild(h1);
div.appendChild(h3);
div.appendChild(h4);

document.body.appendChild(div);
}
});

如果你想用 CSS 设置它们的样式,你可能应该给它们不同的类,或者给 DIV 一个类,例如

div.classList.add("todoItem");

关于javascript - 如何将多个元素附加到一个div?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50186596/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com