开发者

Javascript and `<>...</>` tags

So I recently discovered that I could use <>...</> tags in javascript in Firefox, which is handy when defining blocks of HTML or CSS.

GM_addStyle(<><![CDATA[
  .page { display: block }
  /* ... */
  td { vertical-align: top }
]]></>);
//...
div.innerHTML = <><![CDATA[
  <table class="section">
    <!-- ... -->
  </table>
]]></>;

But I'm not exactly sure what's going on, and I like understanding the syntax that I'm using. What exactly does <>...</> return? I noticed that the escaping works better when I enclose the co开发者_C百科ntents in <![CDATA[...]]>, so what's happening there? Is this Firefox only, or cross-browser?

I tried to look this up online, but ran into the normal google/symbol issue. Plus, most of the results for google CDATA javascript didn't seem relevant.


I believe the empty tags are just a way of writing a root element so that you have something in which to wrap a blob of XML. It's saying "Interpret the children of this root element as XML" and the single child in your case is saying "Interpret this child as a CDATA block."


There's no reason to use an XMLList literal (<>...</>) with only one child, as it's handled as a single XML item anyways. Why not use just <![CDATA[...]]>? Also, <![CDATA[...]]> just returns an XML text node (<![CDATA[]]>.nodeKind() === "text").

This is all part of E4X, which is implemented by ActionScript 3 and both JavaScript engines.


As Elijah said, it's E4X syntax that won't work anywhere but Mozilla. You don't appear to be using it for anything to do with XML, just relying on the implicit toString method of the XML object being the same as the original markup. ECMA-357 (the E4X spec) doesn't specify the exact parse and serialisation rules for XML, so it doesn't guarantee eg. to remove the <![CDATA[ markers for you. IMO relying on this even just on Firefox is questionable.

In any case it doesn't really solve the problems of escaping content for use inside a script block... in particular, the </ sequence is still invalid in HTML4, the whole lot is invalid in XHTML, and you would still have to worry about the sequences </script and ]]> in the content. So you haven't really gained a lot... at best, you've got yourself a multi-line string in external scripts, at the expense of support for all the other browsers. I don't think it's really worth it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜