Search code examples
phpjavascriptnestedquotes

Nested quotes level 4 javascript error


I have the following code (I formated it to more lines, but in my source code I have it in one line, because innerHTML doesn't like new lines somehow - but that isn't the problem...):

<?php
  echo "
    <img 
      src='1.png' 
      onclick='
        document.getElementById(\"my_div\").innerHTML=\"
          <img src=\\\"1.png\\\" onclick=\\\"alert(\\\\\\\"text\\\\\\\");\\\" />
        \";
      '
    />
  ";
?>

And somewhere in the body I have :

<div id="my_div"></div>

So, when I click on the image, i'll have the same image inside my_div. The problem is, that when I click on the 2nd image, javascript doesn't alert anything.

But when I change this:

alert(\\\\\\\"text\\\\\\\");

to this:

alert(MyText); 

and add JavaScript variable MyText:

<script>
  MyText = "text";
</script>

it now works.

I think the problem is with those nested quotes:

\\\\\\\" 

(level 4). Any ideas? Thanks.

EDIT: please don't post here another methods of doing this, I'd like to know why those quotes doesn't work here..

SECOND EDIT: I need that php there, because this is only a piece of my code (in full code I need it to display images in cycle...)


Solution

  • If you want a quote character as data (instead of as an attribute delimiter) in HTML, you represent it as &quot; not \"