[英]appending to the DOM - vanilla javascript
I wanted to practice my vanilla javascript skills since I've been so library-heavy lately.我想练习我的香草 javascript 技能,因为我最近很喜欢图书馆。 My goal was to filter an array of JSON data (by events after 10/01/2015), and then append them as list items to the DOM, with the class being "events", and give the ability to delete events.
我的目标是过滤 JSON 数据数组(按 2015 年 10 月 1 日之后的事件),然后将它们作为列表项附加到 DOM,类为“事件”,并提供删除事件的能力。 Why isn't this working?
为什么这不起作用?
https://jsfiddle.net/youngfreezy/7jLswj9b/ https://jsfiddle.net/youngfreezy/7jLswj9b/
function convertToJSData(arr) {
for (var i = 0; i < arr.length; i++) {
// var from = "10-11-2011";
var from = arr[i].date;
var numbers = from.match(/\d+/g);
var date = new Date(numbers[2], numbers[0] - 1, numbers[1]);
arr[i].date = date;
}
console.log(arr[0].date);
return arr;
}
function getByDate(data) {
convertToJSData(data);
var filterDate = new Date(2015, 09, 01);
return data.filter(function (el) {
return el.date >= filterDate;
});
}
var filteredDates = getByDate(events);
filteredDates.sort(function (a, b) {
return a.date - b.date;
});
console.log(filteredDates.length); //returns 6
var appendHTML = function (el) {
var list = document.getElementById("events");
for (var i = 0; i < filteredDates.length; i++) {
var listItem = filteredDates[i].name;
listItem.className = "event-list";
list.appendChild(listItem);
}
};
appendHTML(document.body);
var deleteEvent = function () {
var listItem = this.parentNode;
var ul = listItem.parentNode;
//Remove the parent list item from the ul
ul.removeChild(listItem);
}
when you do: 当您这样做时:
var listItem = filteredDates[i].name;
listItem.className = "event-list";
list.appendChild(listItem);
listItem
is a string. listItem
是一个字符串。 You cannot append it as a child, you need to create a DOM element and append that: 您不能将其作为子项附加,需要创建一个DOM元素并将其附加:
var newEl = document.createElement('div');
newEl.className = "event-list";
newEl.innerHTML = filteredDates[i].name;
list.appendChild(newEl);
On a separate note, to just focus on the vanilla JS part of the question, maybe something like the following should illustrate the idea more generally:在单独的说明中,只关注问题的香草 JS 部分,也许像下面这样的内容应该更普遍地说明这个想法:
let newElement = document.createElement("div");
newElement.innerHTML += `<ul><li>Item 1</li><li>Item 2</li></ul>`;
newElement.className = "item-list";
document.getElementById("root").append(newElement);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.