实例名称
将HTML转换为JavaScript脚本
实例描述
随着c#的流行,很多时候需要在后台手写HTML代码,为了正确地书写,可以使用本例提供的代码自动生成脚本,然后在后台调用。
实例代码
htmlheadtitle无标题文档-学无忧u00a0u00a0u00a0 function toScriptvalu00a0u00a0u00a0 u00a0u00a0u00a0u00a0u00a0u00a0u00a0u00a0 var value = ;u00a0u00a0u00a0u00a0u00a0u00a0u00a0u00a0 //特殊字符的转换u00a0u00a0u00a0u00a0u00a0u00a0u00a0u00a0 valueu00a0 = \\/gi,"";u00a0u00a0u00a0u00a0u00a0u00a0u00a0u00a0 valArr = "\r\n";//分行u00a0u00a0u00a0u00a0u00a0u00a0u00a0u00a0 value="";u00a0u00a0u00a0u00a0u00a0u00a0u00a0u00a0 for i=0; ; i++u00a0u00a0u00a0u00a0u00a0u00a0u00a0u00a0 u00a0u00a0u00a0u00a0u00a0u00a0u00a0u00a0u00a0 value += i==0 ? "info =" : ""u00a0u00a0u00a0u00a0u00a0u00a0u00a0u00a0u00a0 value += "u00a0 \"" + valArri;u00a0u00a0u00a0u00a0u00a0u00a0u00a0u00a0u00a0 value += i!= ? "\" +\"\\n\"+\n" : "\"\n" ;//字符串的间隔符号u00a0u00a0u00a0u00a0u00a0u00a0u00a0u00a0 u00a0u00a0u00a0u00a0u00a0u00a0u00a0u00a0 value+="\";u00a0u00a0u00a0u00a0u00a0u00a0u00a0u00a0 = value;u00a0u00a0u00a0u00a0 /script
需要在body中添加一个按钮调用上面的方法,代码如下所示:/headbodyinput type=button value="将 HTML 转为 JavaScript" onclick="mytxt"brtextarea id=mytxt cols=60 rows=8u00a0u00a0u00a0 table width="300"u00a0u00a0u00a0 trtd align="right"A/td/tru00a0u00a0u00a0 /table/textarea/body/html
运行效果
难点剖析
本例的重点是对特殊字符的转换。其中用了“replace”和“split”方法。“replace”用来替换指定的字符,“split”用来将字符串分解为数组,分解的依据就是指定的标识。
源码下载