I dont know how to make this onclick work. The var foodId is a string and I need to put quotation marks around it.
$('#results').append('<div onclick="() => cart(' foodId ')"></div>');
CodePudding user response:
You're using jQuery so don't add elements with inline event listeners. Use it to add an element with a class to the page, and then have it listen out for events from those elements.
Here's a basic example.
const items = [ 'orange', 'apple' ];
const button1 = `<button data-food-id="${items[0]}">Add ${items[0]}</button>`;
const button2 = `<button data-food-id="${items[1]}">Add ${items[1]}</button>`;
// Append the button, and then listen out
// for events from its elements with the `add` class
$('#results')
.append(button1)
.on('click', '.add', handleClick);
function handleClick() {
const item = $(this).data('food-id');
console.log(`I have clicked "${item}"`);
}
// We can add a new button, and its events will
// still be recognised
$('#results').append(button2);
.add { margin-right: 1em; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="results"></div>
CodePudding user response:
I use this technique, using JSON.stringify
and escaping "
, &
, <
and so on.
var foodId = `don't "call" me & & <something>`;
function esc_attr(string) {
if (!string) {
return "";
}
return ("" string).replace(/[&<>"'\/\\]/g, function(s) {
return {
"&": "&",
"<": "<",
">": ">",
'"': '"',
"'": ''',
"/": '/',
"\\": '\'
}[s];
});
}
$('#results')
.append('<button onclick="cart(' esc_attr(JSON.stringify(foodId)) ')">click</button>');
function cart(str) {
console.log(str)
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="results"></div>