4

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?

3
  • Inside single quote why would you escape double code? 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. 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. Commented Dec 19, 2012 at 19:12

4 Answers 4

7

See this, its beautiful:

ajaxData += '<div class="menu-item-' + $(this).attr('div') + ' onclick="alert(\'Jquery Function\');"></div>';
Sign up to request clarification or add additional context in comments.

6 Comments

@Mr.Alien most possibly! Being positive you know :p
I'm really sorry! I was tired. This is a jquery variable.
You didn't have to tell its a jQuery variable. Because once its concatenated with + its obviously is JS.
Thank you! However, the code you posted produces <div class="menu-item-purple onclick=" function');"="" alert('jquery=""></div>
should be okay now. I added a space before onclick attribute.
|
2

Dirty escape pheeww...Try this

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

Comments

2
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

1 Comment

Escape the single quote inside alert.
2

This is are you trying to do?

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.