javascript常用方法总结
1、JavaScript:写入HTML输出
document.write("<h1>Thisisaheading</h1>"); document.write("<p>Thisisaparagraph</p>");
2、JavaScript:对事件作出反应
<buttontype="button"onclick="alert('Welcome!')">点击这里</button>
3、JavaScript:改变HTML内容
x=document.getElementById("demo")//查找元素 x.innerHTML="HelloJavaScript";//改变内容
4、JavaScript:改变HTML图像
element=document.getElementById('myimage') element.src="../i/eg_bulboff.gif";
5、改变HTML样式
x=document.getElementById("demo")//找到元素 x.style.color="#ff0000";//改变样式
6、JavaScript对大小写敏感。
JavaScript对大小写是敏感的。
当编写JavaScript语句时,请留意是否关闭大小写切换键。
函数getElementById与getElementbyID是不同的。
同样,变量myVariable与MyVariable也是不同的。
7、提示:一个好的编程习惯是,在代码开始处,统一对需要的变量进行声明。
8、Value=undefined
在计算机程序中,经常会声明无值的变量。未使用值来声明的变量,其值实际上是undefined。在执行过以下语句后,变量carname的值将是undefined:
varcarname;
9、创建JavaScript对象
本例创建名为"person"的对象,并为其添加了四个属性:
person=newObject(); person.firstname="Bill"; person.lastname="Gates"; person.age=56; person.eyecolor="blue";
10、JavaScript表单验证
必填(或必选)项目
下面的函数用来检查用户是否已填写表单中的必填(或必选)项目。假如必填或必选项为空,那么警告框会弹出,并且函数的返回值为false,否则函数的返回值则为true(意味着数据没有问题):
<html> <head> <scripttype="text/javascript"> functionvalidate_required(field,alerttxt) { with(field) { if(value==null||value=="") {alert(alerttxt);returnfalse} else{returntrue} } } functionvalidate_form(thisform) { with(thisform) { if(validate_required(email,"Emailmustbefilledout!")==false) {email.focus();returnfalse} } } </script> </head> <body> <formaction="submitpage.htm"onsubmit="returnvalidate_form(this)"method="post"> Email:<inputtype="text"name="email"size="30"> <inputtype="submit"value="Submit"> </form> </body> </html>
以上所述就是本文的全部内容了,希望大家能够喜欢