最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Adding HTML code with Single Quotes inside jQuery - Stack Overflow

programmeradmin3浏览0评论

I am trying to add this HTML/JavaScript code into a jQuery variable. 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');

Anyone know how I can go around this?

I am trying to add this HTML/JavaScript code into a jQuery variable. 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');

Anyone know how I can go around this?

Share Improve this question edited Dec 12, 2012 at 17:44 Peter O. 32.9k14 gold badges84 silver badges97 bronze badges asked Dec 11, 2012 at 17:52 pufAmufpufAmuf 7,80514 gold badges63 silver badges97 bronze badges 3
  • Inside single quote why would you escape double code? – Lenin Commented Dec 11, 2012 at 17:53
  • 1 Even if you didn't want PHP solution. We actually wrote for JS version. because your + concatenation is for JS but not for PHP. – Lenin Commented Dec 11, 2012 at 19:02
  • tip: in javascript you use " and ' for strings and in both you can use escaping such \', \", and \n. And in the html attributes the standard says the use of " as string delimiter. – Felipe Buccioni Commented Dec 19, 2012 at 19:12
Add a ment  | 

4 Answers 4

Reset to default 7

See this, its beautiful:

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

Dirty escape pheeww...Try this

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

This is are you trying to do?

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

评论列表(0)

  1. 暂无评论