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
4 Answers
Reset to default 7See 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>';"