动态地将Javascript写入新的HTML页面 [英] Dynamically Writting Javascript to a new HTML Page

查看:172
本文介绍了动态地将Javascript写入新的HTML页面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在下面的代码中使用以下代码尝试通过单击按钮动态地将一些javascript动态写入新的html页面。

I have the following code below in which I am using to attempt to dynamically write some javascript into a new html page at the click of a button.

我是但是在尝试这样做时遇到错误我理论上得到未终止的字符串constamnt
,这应该有效:

I am however getting an error when attempting to do so I get "unterminated string constamnt" in theory, this should work:

var html     =  '<!DOCTYPE html>\n'
html    +=  '<html>\n'
html    +=  '<head>\n'
html    +=  '<script type="text/javascript">\n'
html    +=  'function testme() {\n'
html    +=  'alert("the test worked!")\n'
html    +=  '}\n'       
html    +=  '</script>\n'
html    +=  '</head>\n'
html    +=  '<body>\n'
html    +=  '</body>\n'
html    +=  '</html\n'

window.open('','').document.write(html)


推荐答案

你错过了最后一行的收盘>

You are missing a closing > on the last line

html    +=  '</html\n'  <-- Missing a greater than

应该是

html    +=  '</html>\n'

如果代码是内联的而不是外部脚本,则需要分解结束脚本标记。

If the code is inline and not in an external script, you will need to break up the closing script tag.

html    +=  '</scr' + + 'ipt>\n';

也可以使用分号。

现在window.open,document.write行看起来很奇怪。大多数开发人员会把它写成

Now the window.open, document.write line looks strange. Most developers would write it as

var winPop = window.open('','');
winPop.document.open();
winPop.document.write(html);
winPop.document.close();

这篇关于动态地将Javascript写入新的HTML页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆