简体   繁体   English

在jQuery中使用单引号添加HTML代码

[英]Adding HTML code with Single Quotes inside jQuery

I am trying to add this HTML/JavaScript code into a jQuery variable. 我试图将此HTML / JavaScript代码添加到jQuery变量中。 I've managed to insert double quotes by writing is with a backshlash \\" , however the same tactic didn't work for the single quotes: 我设法插入双引号通过写入带反斜杠\\" ,但相同的策略不适用于单引号:

ajaxData += '<div class=\"menu-item-' + $(this).attr('div') + 'onclick=\"alert('Jquery Function');\"></div>';

Specifically, this part onclick=\\"alert('Jquery Function'); 具体来说,这部分onclick=\\"alert('Jquery Function');

Anyone know how I can go around this? 谁知道我怎么能绕过这个?

看到它,它的美丽:

ajaxData += '<div class="menu-item-' + $(this).attr('div') + ' onclick="alert(\'Jquery Function\');"></div>';

肮脏的逃脱pheeww ...试试这个

ajaxData += '<div class="menu-item-' + $(this).attr('div') + 'onclick="alert(\'Jquery Function\');"></div>';
ajaxData += '<div class="menu-item-' + $(this).attr('div') + 'onclick="alert('Jquery Function');"></div>';

add escape \\ for single quotes. 为单引号添加escape \\。 if your string is within single quotes then you can use double quotes without escape but if using single quotes within single quote then you have to insert escape character 如果您的字符串在单引号内,那么您可以使用双引号而不使用转义但如果在单引号中使用单引号,则必须插入转义字符

这是你想做的吗?

$var = "ajaxData += '<div class=\"menu-item-' + \$(this).attr('div') + '" onclick=\"alert(\'Jquery Function\');\"></div>';"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM