最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

JavaScript : how to embed HTML code, how to quote? - Stack Overflow

programmeradmin2浏览0评论

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 plains. So, I would like your help in overing this. Thank you.

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 plains. So, I would like your help in overing this. Thank you.

Share Improve this question edited Nov 12, 2011 at 11:13 Rob W 349k87 gold badges807 silver badges682 bronze badges asked Nov 12, 2011 at 11:09 user690182user690182 2791 gold badge8 silver badges21 bronze badges 1
  • Don't use document.write(). There are better ways to change the DOM. See innerHTML or appendChild() for example. – the_drow Commented Nov 12, 2011 at 11:17
Add a ment  | 

3 Answers 3

Reset to default 3

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

Read the "Escaping characters" part of this page: https://developer.mozilla/en/JavaScript/Guide/Values,_Variables,_and_Literals And I think it will all make sense.

发布评论

评论列表(0)

  1. 暂无评论