我目前正在与
建立论坛\json\myfile.json
我能够获取使用JSON api但无法删除它们的请求。
这是我的代码:
JSON:
[
{
"title": "Hello World !",
"content": "1111111"
},
{
"title": "Lorem Ipsum",
"content": "22222222"
},
{
"title": "azertyuiop",
"content": "33333333"
}
]
HTML:
<div id="element"></div>
<div id="newElement">
<input id="newTitle" type="text" value="">
<input id="newContent" type="text" value="">
<button type="button" name="addElement" onclick="addElement()">Add</button>
</div>
JavaScript的:
'use strict';
function loadJSON(callback) {
var xobj = new XMLHttpRequest();
xobj.overrideMimeType("application/json");
xobj.open('GET', 'json/elements.json', true);
xobj.onreadystatechange = function() {
if (xobj.readyState == 4 && xobj.status == "200") {
callback(xobj.responseText);
}
};
xobj.send(null);
}
function getElements() {
loadJSON(function(response) {
var elements = JSON.parse(response);
var containerElement = document.getElementById("element");
var titleElement;
var contentElement;
var deleteElement;
for (var i = 0; i < elements.length; i++) {
titleElement = document.createElement("h1");
contentElement = document.createElement("p");
deleteElement = document.createElement("button");
containerElement.appendChild(titleElement);
containerElement.appendChild(contentElement);
containerElement.appendChild(deleteElement);
titleElement.innerHTML = elements[i].title;
contentElement.innerHTML = elements[i].content;
deleteElement.innerHTML = "Delete";
deleteElement.addEventListener('click', function() {
console.log(titleElement[i]);
console.log(contentElement[i]);
});
}
});
}
function addElement() {
loadJSON(function(response) {
var elements = JSON.parse(response);
var newTitle = document.getElementById('newTitle').value;
var newContent = document.getElementById('newContent').value;
console.log("Title: " + newTitle + " " + "Content: " +
newContent);
});
}
getElements();
我查看了闭包是如何工作的,但我不知道如何将它们应用到我的代码中,在我记录undefined
和contentElement
后,它会返回titleElement
。< / p>
答案 0 :(得分:-1)
你真的很亲近。获取undefined
和contentElement
的{{1}}的问题是described in this question's answers,但那里的答案是一般性的,并不能为您提供最简单的处理方式在你的情况下。
见评论:
titleElement
另外,没有必要在function getElements() {
loadJSON(function(response) {
var elements = JSON.parse(response);
var containerElement = document.getElementById("element");
var entryElement;
var titleElement;
var contentElement;
var deleteElement;
for (var i = 0; i < elements.length; i++) {
// Create a container for the entry; let's give it a class we'll
// use later as well
entryElement = document.createElement("div");
entryElement.className = "entry";
titleElement = document.createElement("h1");
contentElement = document.createElement("p");
deleteElement = document.createElement("button");
// Put these in the entry's container
entryElement.appendChild(titleElement);
entryElement.appendChild(contentElement);
entryElement.appendChild(deleteElement);
titleElement.innerHTML = elements[i].title;
contentElement.innerHTML = elements[i].content;
deleteElement.innerHTML = "Delete";
deleteElement.addEventListener('click', function() {
// Here, `this` refers to the delete button that was clicked;
// remove its parent element:
var parent = this.parentNode;
parent.parentNode.removeChild(parent);
});
// Add the entry to the main container
containerElement.appendChild(entryElement);
}
});
}
中重新加载JSON,只需在页面中添加一个新元素。事实上,既然我们想在从JSON创建元素和添加新元素时都这样做,那么让我们将它放在一个函数中,然后重用该函数:
addElement
&#13;
'use strict'
var json = '[{' +
'"title": "Hello World !",' +
'"content": "1111111"' +
'},' +
'{' +
'"title": "Lorem Ipsum",' +
'"content": "22222222"' +
'},' +
'{' +
'"title": "azertyuiop",' +
'"content": "33333333"' +
'}' +
']';
function loadJSON(callback) {
// Simulate the ajax
setTimeout(callback, 200, json);
/*
var xobj = new XMLHttpRequest();
xobj.overrideMimeType("application/json");
xobj.open('GET', 'json/elements.json', true);
xobj.onreadystatechange = function() {
if (xobj.readyState == 4 && xobj.status == "200") {
callback(xobj.responseText);
}
};
xobj.send(null);
*/
}
function addElement(title, content) {
// Create a container for the entry
var entryElement = document.createElement("div");
entryElement.className = "entry";
// And the things to put in it
var titleElement = document.createElement("h1");
var contentElement = document.createElement("p");
var deleteElement = document.createElement("button");
// Put these in the entry's container
entryElement.appendChild(titleElement);
entryElement.appendChild(contentElement);
entryElement.appendChild(deleteElement);
// You might consider HTML-escaping things, here's how
titleElement.appendChild(document.createTextNode(title));
contentElement.appendChild(document.createTextNode(content));
deleteElement.innerHTML = "Delete";
deleteElement.addEventListener('click', function() {
// Here, `this` refers to the delete button that was clicked;
// remove its parent element:
var parent = this.parentNode;
parent.parentNode.removeChild(parent);
});
// Add the entry to the main container
document.getElementById("element").appendChild(entryElement);
}
function getElements() {
loadJSON(function(response) {
var elements = JSON.parse(response);
for (var i = 0; i < elements.length; i++) {
// Call our reusable function
addElement(elements[i].title, elements[i].content);
}
});
}
function addElementClick() {
// Just call our reusable function
addElement(document.getElementById('newTitle').value, document.getElementById('newContent').value);
}
getElements();
&#13;
请注意,我已将原始<div id="element"></div>
<div id="newElement">
<input id="newTitle" type="text" value="">
<input id="newContent" type="text" value="">
<button type="button" name="addElement" onclick="addElementClick()">Add</button>
</div>
重命名为addElement
并使用新的addElementClick
函数接受标题和内容作为参数。
如果在某个阶段你想要重建addElement
数组,你可以通过从DOM中检索数据来做到这一点:
elements
function getElementsFromUI() {
var elements = [];
document.querySelector(".entry").forEach(function(entryElement) {
elements.push({
title: entryElement.querySelector("h1").innerHTML,
content: entryElement.querySelector("p").innerHTML
});
});
return elements;
}
返回的NodeList
最近才获得querySelectorAll
,但您可以轻松地在旧版浏览器中对其进行填充:
forEach
直播示例:
if (typeof NodeList !== "undefined" && NodeList.prototype && !NodeList.prototype.forEach) {
Object.defineProperty(NodeList.prototype, "forEach", {
value: Array.prototype.forEach,
configurable: true,
enumerable: true
});
}
&#13;
'use strict'
var json = '[{' +
'"title": "Hello World !",' +
'"content": "1111111"' +
'},' +
'{' +
'"title": "Lorem Ipsum",' +
'"content": "22222222"' +
'},' +
'{' +
'"title": "azertyuiop",' +
'"content": "33333333"' +
'}' +
']';
if (typeof NodeList !== "undefined" && NodeList.prototype && !NodeList.prototype.forEach) {
Object.defineProperty(NodeList.prototype, "forEach", {
value: Array.prototype.forEach,
configurable: true,
enumerable: true
});
}
function loadJSON(callback) {
// Simulate the ajax
setTimeout(callback, 200, json);
/*
var xobj = new XMLHttpRequest();
xobj.overrideMimeType("application/json");
xobj.open('GET', 'json/elements.json', true);
xobj.onreadystatechange = function() {
if (xobj.readyState == 4 && xobj.status == "200") {
callback(xobj.responseText);
}
};
xobj.send(null);
*/
}
function addElement(title, content) {
// Create a container for the entry
var entryElement = document.createElement("div");
entryElement.className = "entry";
// And the things to put in it
var titleElement = document.createElement("h1");
var contentElement = document.createElement("p");
var deleteElement = document.createElement("button");
// Put these in the entry's container
entryElement.appendChild(titleElement);
entryElement.appendChild(contentElement);
entryElement.appendChild(deleteElement);
// You might consider HTML-escaping things, here's how
titleElement.appendChild(document.createTextNode(title));
contentElement.appendChild(document.createTextNode(content));
deleteElement.innerHTML = "Delete";
deleteElement.addEventListener('click', function() {
// Here, `this` refers to the delete button that was clicked;
// remove its parent element:
var parent = this.parentNode;
parent.parentNode.removeChild(parent);
});
// Add the entry to the main container
document.getElementById("element").appendChild(entryElement);
}
function getElements() {
loadJSON(function(response) {
var elements = JSON.parse(response);
for (var i = 0; i < elements.length; i++) {
// Call our reusable function
addElement(elements[i].title, elements[i].content);
}
});
}
function addElementClick() {
// Just call our reusable function
addElement(document.getElementById('newTitle').value, document.getElementById('newContent').value);
}
function getElementsFromUI() {
var elements = [];
document.querySelectorAll(".entry").forEach(function(entryElement) {
elements.push({
title: entryElement.querySelector("h1").innerHTML,
content: entryElement.querySelector("p").innerHTML
});
});
return elements;
}
document.getElementById("btnShow").addEventListener("click", function() {
console.log(getElementsFromUI());
});
getElements();
&#13;
.as-console-wrapper {
max-height: 100% !important;
}
&#13;
或者,您可以保留<input type="button" id="btnShow" value="Show Elements">
<div id="element"></div>
<div id="newElement">
<input id="newTitle" type="text" value="">
<input id="newContent" type="text" value="">
<button type="button" name="addElement" onclick="addElementClick()">Add</button>
</div>
数组的副本,并确保您删除条目和删除条目的DOM结构,类似的确保添加完成并行,但是你要编写代码来维护两个事物列表,这几乎不可避免地导致更新一个但忘记更新另一个。各种&#34;现场绑定&#34;库试图通过让你只维护你的元素数组然后根据它更新DOM来帮助那里,比如Knockout,Vue,React,Angular和其他十几个。 (有些很简单,很容易放到任何项目中;有些则更复杂,并且采取&#34;你以我的方式做你的应用程序&#34;接近。:-))对于任何非平凡的事情,它都是&#39;可能值得一看这样的东西。