与页面的交互
简单计算机的编辑
<body>
第一个数:<input type="text" id="one" value="" /><br />
第二个数:<input type="text" id="two" value="" /><br />
运算方式:
<input type="button" id="" value="+" onclick="cal('+')"/>
<input type="button" id="" value="-" onclick="cal('-')"/>
<input type="button" id="" value="*" onclick="cal('*')"/>
<input type="button" id="" value="/" onclick="cal('/')"/><br />
运算结果:<input type="text" id="result" value="" />
<script type="text/javascript">
function cal(y){
//获取文本框输入的值
var one=document.getElementById("one").value
var two=document.getElementById("two").value
if(y=="+"){
//运算
var result=Number(one)+Number(two)
}else if(y=="-"){
var result=Number(one)-Number(two)
}else if(y=="*"){
var result=Number(one)*Number(two)
}else if(y=="/"){
var result=Number(one)/Number(two)
}else{
undefined
}
//将运算结果赋值给第三个文本框
document.getElementById("result").value=result
}
</script>
</body>
实现的效果为
属性、方法和事件
Javascript中的构造函数及对象
构造函数的编写方法有三种,分别是:
<body>
<script type="text/javascript">
//自定义对象
var student=new Object()
//给对象设置一些属性
student.stuID="1001"
student.stuName="张三"
student.className="移动213"
//给对象设置函数
student.sayHello=function(){
console.log("大家好")
}
console.log(student)
// function 函数名(参数列表){函数体}
// 赋值式声明函数
// var test=function(){
// console.log("aa")
// }
// test()
//使用构造函数
function teacher(tid,tname){
//构造函数中的this指的是当前对象
this.tid=tid
this.tname=tname
this.Eat=function(){
console.log("吃饭")
}
}
//实例化一个对象
var t1=new teacher("1","张三")
t1.Eat()
console.log(t1.tid,t1.tname)
console.log(t1)
//其他方式
var stu={
stuid:"1002",
stuname:"李四",
study:function(){
console.log("学习")
}
}
stu.study()
console.log(stu.stuid)
</script>
</body>
运行结果如下:
类是对象的抽象,对象是类的具体
对象分为三类、如下
函数及对象的实例:
<body>
email:<input type="text" name="email" id="email" value="" />
<input type="button" name="" id="" value="验证" onclick="checkEmail()" />
<script type="text/javascript">
//字符串对象
//获取一个字符串的长度
var str="Hello Worldd!"
console.log("该字符串的长度是:"+str.length)
console.log(str.charAt(1))
console.log(str.indexOf("l"))
console.log(str.indexOf("a"))//-1 当查找的字符不存在时,返回-1
//123@qq.com
//邮箱中必须包含@和.,且@必须在.前面
function checkEmail(){
var email=document.getElementById("email").value
if (email.indexOf("@")==-1) {
alert("该邮箱地址中不包含@")
}else if(email.indexOf(".")==-1){
alert("该邮箱地址中不包含.")
}else if(email.indexOf("@")>email.indexOf(".")){
alert("该邮箱地址中@必须在.前面")
}else{
alert("该邮箱地址正确!")
}
}
console.log(str.substring(0,4))
</script>
</body>
运行结果为
对象的一些方法(参数列表)/属性