简体   繁体   中英

JavaScript delete-function does not work (absolute Newbie)

First off: sorry for that awful Code. I am an absolute beginner and this is my very first JS code ever and I had to code it under time-pressure (not good).

The task was to code a guest book. I have a function that creates a new div per entry and appends it to the last one (this part works well).

var lastid = 2;

function eintragen() {

    ...

    var divC = document.createElement('div');

    var ident='item'+lastid;

    divC.innerHTML = '<table id="'+ident+'" class="eintrag center">  
    <tr><td>Name:</td><td>'+name2+'</td></tr><tr>
    <td>Email:</td><td>'+email2+'</td></tr> 
    <tr><td>Eintrag</td><td>'+nachricht2+'</td></tr>
    <tr><td></td><td><button class="buttonklein"value="loeschen"

    ***onclick="loeschen('+ident+')"***

    >Eintrag löschen</button></td></t></table><hr>';



    **divC.setAttribute('id',ident);**

    var add = document.getElementById('item1');
    add.appendChild(divC);


    lastid+=1;

    ...

}  

I tried do highlight the relevant part. As you can see, I gave the id to the divC twice, because after testing, I figured out, that it did not work in the "divC.innerHTML"-segment.

Every entry has an own delete-button, which should - you guess it - delete that associated entry.After clicking the button, the function starts, but then nothing happens.

function loeschen(itemid) {

   var sitem = document.getElementById(itemid); 
   sitem.parentNode.removeChild(sitem);
}

I guess, since assigning the ID to the divC did not work in the "divC.innerHTML" part, it also does not work to assign it as a parameter to the "onclick" -attribute.

If I replace itemid with something concrete like 'item4' in the loeschen-function, it does delete entry number 4, so I guess the mistake is in the divc.innerHTML-part.

Question: Where did I go wrong? Any wrong '' oder ""? How can i give every button the current itemid? everything worked fine for the other variables like name oder email, so I have absolutely no clue.

Thanks so much in advance and sorry for my bad style. I will work on this in the future.

User Teemu found the answer super fast and was a great help. It was indeed bad syntax in the divC.innerHTML-segment. This does the job:

    divC.innerHTML = `<table id="${ident}" class="eintrag center">  
    <tr><td>Name:</td><td>${name2}</td></tr><tr>
    <td>Email:</td><td>'+email2+'</td></tr> 
    <tr><td>Eintrag</td><td>${nachricht2}</td></tr>
    <tr><td></td><td><button class="buttonklein" value="loeschen"
    onclick="loeschen('${ident}')">Eintrag löschen</button>
    </td></t></table><hr>`;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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