skip to Main Content

This is my code

    function render(img, name, price) {
        var row = `
            <a class="ProductCard" href="#" onclick="page('${numberFolder}')">
            <img src="${img}">
            <h1>${name}</h1>
            <p>${price}</p>
            </a>
        `;
    document.querySelector('#main').insertAdjacentHTML('beforeend', row);
    }

I want to execute the page() function but I can’t, JavaScript detects it as a new function because it’s inside the string. When I check the error I get this

Uncaught ReferenceError: page is not defined at HTMLAnchorElement.onclick

this is the page() function (not finished yet)

function page(folderNum){
    rowOrder = `HTML-HERE`
    const productDetails = database.ref(`/products/${folderNum}`);
    productDetails.on('value', (snapshot) => {
    const details = snapshot.val();
    console.log(details)
   })
}

3

Answers


  1. To execute a function inside a string in JavaScript, you can use the eval() function. However, it is important to be cautious when using eval() as it can potentially introduce security risks if used with untrusted or user-generated data.

    Login or Signup to reply.
  2. Select the a tag by doing for example: let aTag = row.children[0]. Than you can do: aTag.onclick = () => page('${numberFolder}'). This is probably the safest way to do it. For solid and change proof code you can select the aTag by querying on a class name.

    Edit: You don’t need to define functions in text and you really shouldn’t ever.

    Login or Signup to reply.
  3. I suspect your page function is not in scope when you click the added content. Because if it’s placed correctly, this technique should work fine, as the following snippet demonstrates:

    function render(title, value) {
       const row = `
         <div>
           <a class="ProductCard" href="#" onclick="page('${value}')">
             <p>${title}: ${value}</p>
           </a>
         </div>`;
        document.querySelector('#main').insertAdjacentHTML('beforeend', row);
    }
    
    function page(x) {
      alert(x)
    }
    
    render ('Meaning of life', 42)
    render ('Bottles of beer', 99)
    <div id="main"><h3>Click these to see that it works</h3></div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search