Here is the JSFiddle link for my project, you can see the full app.js here... http://ift.tt/2Dfvjmh
Basically I am trying to build a contact diary where you create new contacts and then be able to edit or delete them at a later stage...
on line 85 onwards is the click event for the Edit and Delete buttons, I have got these buttons working to some extent however I know that the way I have written this part of the code is incorrect because I have repeated loops and if statements.
I have tried putting these repeated parts of the code into functions but then the app crashes and I receive different errors ie:- so and so is not defined, functions not returning the correct value etc. I have tried a couple of things to overcome these errors but still cant get it to work and or get my head around this.
Please could you show/tell me how to make this code better in terms of DRY, and readability. Thank you.
Here is the part of the code in question -
//Click event for Edit and Delete buttons.
contacts.addEventListener("click", (e) => {
if (e.target.tagName === "BUTTON") {
const button = e.target;
const ul = button.parentNode;
if (button.textContent === "Edit") {
for (var i = 0; i < contactsBook.length; i++) {
if (contactsBook[i].firstName === ul.getAttribute('data-person')) {
const ulChild = ul.childNodes;
for (var j = 0; j < ulChild.length; j++) {
if (ulChild[j].tagName === "LI") {
const items = ulChild[j];
const input = document.createElement('input');
input.type = 'text';
input.value = items.textContent;
items.textContent = "";
items.insertBefore(input, ulChild.childNodes);
button.textContent = 'Save';
};
};
};
};
} else if (button.textContent === "Save") {
for (var i = 0; i < contactsBook.length; i++) {
if (contactsBook[i].firstName === ul.getAttribute('data-person')) {
const ulChild = ul.childNodes;
for (var j = 0; j < ulChild.length; j++) {
if (ulChild[j].tagName === "LI") {
console.log(ulChild[j]);
};
};
};
};
} else if (button.textContent === "Delete") {
contacts.removeChild(ul);
for (var i = 0; i < contactsBook.length; i++) {
if (contactsBook[i].firstName === ul.getAttribute('data-person')) {
contactsBook.splice(i,1);
localStorage.setItem('addbook', JSON.stringify(contactsBook));
};
};
};
};
});
Thank you for your help!
Aucun commentaire:
Enregistrer un commentaire