简体   繁体   中英

JavaScript : how to embed HTML code, how to quote?

Given that I have a JavaScript section in my HTML page like :

<script language="JavaScript">
...
</script>

I am aware of the function : document.write("Hello World") ;

But, how can I can include the following HTML :

<select name="database_subcollection" multiple="true" size="5" onsubmit="document.getElementById('MAIN').submit()">

If I write it like :

document.write('<select name="database_subcollection" multiple="true" size="5" onsubmit="document.getElementById('MAIN').submit()">') ;

It complains. So, I would like your help in overcoming this. Thank you.

You have to escape (double) quote characters, by prefixing an escape character: \\ .

Possible ways to escape a double quote:

  • \\" (JavaScript)
  • \\x22 (JavaScript)
  • &quot (HTML attribute value / plain HTML)

Your example with single quotes didn't work, because the attribute contained a single quote. Replace the ' in the attribute by \\' or &quot; to solve it.

document.write('<select name="database_subcollection" multiple="true" size="5" onsubmit="document.getElementById(\'MAIN\').submit()">') ;

Using:

document.write('<select name="database_subcollection" multiple="true" size="5" onsubmit="document.getElementById(\'MAIN\').submit()">');

You needed to escape ('MAIN') with \\ eg (\\'MAIN\\') assuming containing quotes are single quotes.

Working Example

阅读此页面的“转义字符”部分: https : //developer.mozilla.org/en/JavaScript/Guide/Values,_Variables,_and_Literals而且我认为这都是有道理的。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM