简体   繁体   中英

How can I pass in dynamic arguments with template literals?

I have some very simple code


function createAnswerElement(answer, index) {
  const key = `${answer}-${index}`;

  return `
    <p class="delete" onclick=someSillyFunc(${key})>x</p>
    `;
}

function someSillyFunc(key) {
  console.log(key);
}

The "p tag" gets appended to a div. If I click on the "p tag" with either no parameters or with hardcoded parameters it works just fine. The issue is when I try and use template literals to dynamically pass the variable key to the function. After doing this I constantly get an error in the console "Uncaught SyntaxError: missing ) after argument list."

I have tried wrapping the key variable in quotes and all sorts of other things but cannot get this to work. What am I missing?

You forgot to wrap function around " " in onclick

return `
    <p class="delete" onclick="someSillyFunc(${key})">x</p>
    `;

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