Why does the location of my string declaration affect whether my html encoded entities will be displayed properly?
<p>In adding a new feature to a web app, I need to dynamically set the value of a Button object.  It happens that I need to put some html-encoded unicode characters in the value.  In implementing this I found that the location in which I define the characters determines whether or not they are displayed properly.  If I define the character in the onclick event itself, they character is displayed properly.  If I define it in a function or at the top level, it is displayed as literal text.</p>

<p>I have distilled my issue into the following sample HTML/JS (note that my ultimate issue is unicode characters but I'm using lt/gt as examples):</p>

<pre><code>&lt;html&gt;&lt;body&gt;
&lt;script type="text/javascript"&gt;
    var tlabel3 = '&amp;gt; foo &amp;lt;';
    function ChangeName2() {
        document.getElementById('button2').value = '&amp;gt; foo &amp;lt;';
    }
    function ChangeName3() {
        document.getElementById('button3').value = tlabel3;
    }
    function ChangeName4(label4) {
        document.getElementById('button4').value = label4;
    }
&lt;/script&gt;
&lt;input type=button id=button1 value="&amp;lt; foo &amp;gt;"&gt; - &lt;a href=# onclick="document.getElementById('button1').value = '&amp;gt; foo &amp;lt;'"&gt;Clicky&lt;/a&gt;
&lt;HR&gt;
&lt;input type=button id=button2 value="&amp;lt; foo &amp;gt;"&gt; - &lt;a href=# onclick="ChangeName2()"&gt;Clicky&lt;/a&gt;
&lt;HR&gt;
&lt;input type=button id=button3 value="&amp;lt; foo &amp;gt;"&gt; - &lt;a href=# onclick="ChangeName3()"&gt;Clicky&lt;/a&gt;
&lt;HR&gt;
&lt;input type=button id=button4 value="&amp;lt; foo &amp;gt;"&gt; - &lt;a href=# onclick="ChangeName4('&amp;gt; foo &amp;lt;')"&gt;Clicky&lt;/a&gt;
&lt;/body&gt;&lt;/html&gt;
</code></pre>

<p>In my tests in IE8, Safari, Chrome, and FF3.6, this behaves the same - Buttons 1 and 4, which have the characters defined in the onclick handler, work properly.  Buttons 2 and 3, having the characters defined elsewhere, display the literal <code>&amp;gt;</code> string.</p>

<p>My question is, why does the location of the string definition matter?  I have a work around, but because all four browsers work the same way I feel like I'm missing knowledge some fundamental working of Javascript.</p>

<p>Thanks</p>
