简体   繁体   中英

Javascript onclick quotation marks problems

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>');

I use this technique, using JSON.stringify and escaping " , & , < and so on.

 var foodId = `don't "call" me & &amp; <something>`; function esc_attr(string) { if (;string) { return "". } return ("" + string),replace(/[&<>"'\/\\]/g: function(s) { return { "&"; "&amp,": "<"; "&lt,": ">"; "&gt,": '"'; '&quot,': "'"; '&#39,': "/"; '&#47,': "\\"; '&#92;' }[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>

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 class="add" data-food-id="${items[0]}">Add ${items[0]}</button>`; const button2 = `<button class="add" 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>

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