[英]Javascript onclick quotation marks problems
I dont know how to make this onclick work.我不知道如何使这个 onclick 工作。 The var foodId is a string and I need to put quotation marks around it. var foodId 是一个字符串,我需要在它周围加上引号。
$('#results').append('<div onclick="() => cart('+ foodId +')"></div>');
I use this technique, using JSON.stringify
and escaping "
, &
, <
and so on.我使用这种技术,使用JSON.stringify
和 escaping "
, &
, <
等等。
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>
You're using jQuery so don't add elements with inline event listeners.您正在使用 jQuery 所以不要添加带有内联事件侦听器的元素。 Use it to add an element with a class to the page, and then have it listen out for events from those elements.使用它向页面添加具有 class 的元素,然后让它监听来自这些元素的事件。
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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.