How to use a parameter function in the onclick attribute of Javascript?

Asked

Viewed 98 times

1

I’m starting to study JS and came across a problem. I’m following a tutorial to make an entire app lists, and when I tried to create a function to delete the whole I had a problem.

The function in question should carry a parameter related to the position of the whole within a vector and so it could erase it. I’m trying to do this using setAttribute with a hyperlink element (a), as I show in the code below.

function mostrarItens() {
  for (var item of itens) {
    var itemElement = document.createElement("li");
    var itemText = document.createTextNode(item);
    itemElement.appendChild(itemText);

    var linkElement = document.createElement("a");
    var pos = itens.indexOf(item);
    linkElement.setAttribute("onclick", "remover(" + pos + ");");
    var linkText = document.createTextNode("Remover");
    linkElement.appendChild(linkText);
    linkElement.style.marginLeft = "5px";
    linkElement.setAttribute("href", "#");
    itemElement.appendChild(linkElement);

    ulElement.appendChild(itemElement);
  }
}

function remover(pos) {
  itens.splice(pos, 1);
  mostrarItens();
}

Whenever I click on the link created to delete the whole I get an error saying that the remove function does not exist.

I would like to know what I am doing wrong. I have tried several things and so far nothing.

From now on, thank you very much.

  • remover is a function declared in the global scope, so it should be accessible by its element. Would this code you posted be within some non-global scope? As for example within a IIFE?

  • Hello John, please create an example with HTML that plays the problem here so we can help you.

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.