在 HTML 中,<script>用来向 HTML 中插入 VBScript。换句话说,写好的 VBS 脚本必须写在<script>和</script>,并且需要使用type属性来定义脚本语言的类型为text/vbscript。另外,需要注意的是,vbscript 是不区分大小写的,是否需要大小写要按照工作要求来定。
VBS 输出
当 VBScript 被用在 Web 服务器上的 ASP 页面时,语句response.write()产生输出;当使用 IE 来测试时,语句document.write()来产生输出(这点好像与 JavaScript 是类似的)。不同类型的变量在输出时需要用到&和""符号,比如:
1 2 3
Dim name name="xxx" document.write("My name is:"&name)
<!DOCTYPE html> <html> <body> <scripttype="text/vbscript"> i = hour(time) if i = 9 then document.write("Just started...!") elseif i = 11 then document.write("Hungry!") elseif i = 12 then document.write("Ah, lunch-time!") elseif i = 17 then document.write("Time to go home!") else document.write("Unknow") end if </script> </body> </html>
<!DOCTYPE html> <html> <body> <scripttype="text/vbscript"> for i = 0 to 5 document.write("The number is " & i & "<br>") next </script> </body> </html>
运行结果:
1 2 3 4 5 6
The number is 0 The number is 1 The number is 2 The number is 3 The number is 4 The number is 5
看来,0 to 5是从 0 到 5,得运行 6 次。如果为了在不改变边界条件的情况下,减少循环次数,可以使用Step关键字来完成,看下面这个例子:
1 2 3 4 5 6 7 8 9 10
<!DOCTYPE html> <html> <body> <scripttype="text/vbscript"> for i = 0 to 5 step 2 document.write("The number is " & i & "<br>") next </script> </body> </html>
<!DOCTYPE html> <html> <body> <scripttype="text/vbscript"> for i = 1 to 10 document.write("The number is " & i & "<br>") if i = 5 then exit for next </script> </body> </html>
运行结果:
1 2 3 4 5
The number is 1 The number is 2 The number is 3 The number is 4 The number is 5
For Each…Next
For Each...Next针对集合中的每个项目或者数组中的每个元素来重复运行某段代码,直接看下面这个例子:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
<!DOCTYPE html> <html> <body> <scripttype="text/vbscript"> dim cars(2) cars(0) = "Volvo" cars(1) = "Saab" cars(2) = "BMW" for each x in cars document.write(x & "<br>") next </script> </body> </html>
Do…Loop
类似 C 语言的do-while,直接看例子:
1 2 3 4 5 6 7 8 9 10 11 12
<!DOCTYPE html> <html> <body> <scripttype="text/vbscript"> i = 0 dowhile i < 10 document.write(i & "<br>") i = i + 1 loop </script> </body> </html>