Home > Blockchain >  Function is undefined even if it's properly defined
Function is undefined even if it's properly defined

Time:05-03

I'm trying to call openFormPreview(e), which is an async function, from an onclick event. It's defined but console keep giving me the error:

Uncaught ReferenceError: openFormPreview is not defined

Here's the code

async function openFormPreview(element) {
  //Do some works
  //Get the element
  console.log(element)
  const dcid = element.getAttribute("data-concern-id");
  //Set data
}

function presentData(doc) {
  //Some other codes
  let a = document.createElement("div");
  a.classList.add("concern-item", "dt-cont-surface");
  a.setAttribute("data-concern-id", doc.id);
  a.setAttribute('onclick', 'openFormPreview(this)');
  //More codes
}
<div  data-concern-id="jbTFRy0SFxiHRD29NiL3" onclick="openFormPreview(this)"><span >First Name</span> <span ><span >12</span> - <span >1A</span></span><span >jbTFRy0SFxiHRD29NiL3</span></div>

They are both in the same js file and linked properly with the HTML file.

CodePudding user response:

The string you are setting as the onclick attribute is being evaluated in a scope where openFormPreview is not defined. (Note that your [mcve] has been made too minimal so does not show the different scopes, and thus doesn't actually reproduce the problem).

Don't use the onclick attribute. Use addEventListener instead. That will use the current scope.

a.addEventListener('click', event => openFormPreview(event.currentTarget));

CodePudding user response:

Maybe you should think about placing await word in your code

  • Related