简体   繁体   中英

JavaScript: add an Eventlistener, that executes a function using the elements Parameter

I have a list of html elements, that have an attibute taskNr .

What I'm trying to achieve: when one of those elements is clicked, another element should be deleted. The id of the element to delete is "task" and the taskNr from the clicked element.

I have tried this:

var tasknumbers = [];

// fügt eventlistener für button removetask hinzu
function activateremovetasklistener(){
    var removeBtns = document.getElementsByClassName("fa fa-times-circle floatright fa-fw notfirst");
    for (i = 0; i < removeBtns.length; i++) {
       tasknumbers[i] = removeBtns[i].getAttribute("taskNr");
       removeBtns[i].addEventListener("click", function() {removeTask(i);});
    };

}

//entfernt Task bei Klick auf X
function removeTask(index){
    var taskNr = tasknumbers[index];
    var taskClass = document.getElementById("task" + taskNr);
    taskClass.remove();
}

Instead of the taskNr of the element having the Eventlistener it uses the tasknr from the Array.

How do I fix this?

It seems like you are overwriting tasknumber. Remove tasknumber from the click function, I guess this should work!

for (i= 0; i< removeBtns.length; i++) {
    var tasknumber = removeBtns[i].getAttribute("taskNr");
    removeBtns[i].addEventListener("click", function() {
            var taskClass = document.getElementById("task" + tasknumber);
            taskClass.remove();

    });
};

The problem is, that the Funktion gets the wrong Parameter. this Can be solved by giving it the Event, causing the Eventlistener to be activated, as parameter. So you can get the right taskNr inside the function.

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