I wonder why the following code will choke Javascript? (so the first link works, but the second doesn't) Thanks. <a href="#" onclick='changeIt("hello world"); return false;'>Click me</a> <a href="#" onclick='changeIt("hello " world"); return false;'>Click me</a> <div id="divContent"></div> <script> function changeIt(title) { document.getElementById('divContent').innerHTML = title + " " + new Date(); } </script> Code (markup):
on the other hand, this will work: <a href="#" id="link1">Click me</a> <a href="#" id="link2">Click me</a> <div id="divContent"></div> <script> document.getElementById('link1').onclick = function() { changeIt("hello world"); return false; } document.getElementById('link2').onclick = function() { changeIt("hello " world"); return false; } function changeIt(title) { document.getElementById('divContent').innerHTML = title + " " + new Date(); } </script> Code (markup):
I think the problem is that the " is not enclosed in <script> tags and is being converted by the browser's HTML parser before it hits Javascript. The second example works because " is inside the <script> tags
so it looks like <a href="#" onclick='changeIt("hello " world"); return false;'>Click me</a> is the same as <a href="#" onclick='changeIt("hello " world"); return false;'>Click me</a> and for sure that will choke. i think someone told me that any value part of an attribute is first parsed as HTML. I just can't find where this is formally stated as a rule.
If you use Firebug and inspect the element that's exactly what you'll see. I'm afraid I don't know where you'd find this formally stated but it makes sense - the document has to be parsed first as HTML for the browser to know which bits are Javascript
really? does that mean onclick='changeIt("hello " world");' will also work? since ' is the single quote but i think it won't work as i tried the " version with single quote inside and it didn't work onclick="changeIt('hello');"
No that causes a different problem - the " breaks the HTML parser which is looking for a closing ' to the onclick attribute
i meant to type in & #039; for the single quote... but i think the forum program changed it to the single quote... the real thing i was wondering is <a href="#" onclick="alert(1);">Click me</a> will work too? it seems like it will not work. is only the value part of the attribute being parsed as HTML? thanks.