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
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.
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.
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: