Javascript从入门到精通 - 指南

JavaScript教程

js介绍

js和java没有任何关系!!!
用处:
网页搜索、地图、网页游戏、股票网站、用户输入的校验
对网页元素编程的控制

  • js要使用包裹起来

  • js是脚本语言,不能独立运行

  • 配合其他语言html php asp aspx jsp

  • js是解释性语言,使用浏览器执行

js是基于bs的:browser and server
js是事件驱动型语言:
需要用户触发事件
js是弱类型语言,不需要指定类型:
var num1=4;
var num2=100;
var name=“xiaoming”
使用typeof()查看变量类型

给变量取名的
时候不要取关键字

  • 注释方法:
    //或者/**/
    alert是区分大小写的

js的变量

  • 基本数据类型:
    整数、实数、布尔、字符串
    复合数据类型:
    数组、对象
    特殊数据类型
    null undefined

  • 前面加0为八进制
    var n1=0123;
    前面为0x为十六进制
    var n2=0x8a;
    前面什么都没有为十进制

  • 使用praseInt强制转化为整型
    使用parseFloat强制转化为浮点型

  • 若数字出现异常会出现如下情况:
    NaN not a number
    infinity无限大

  • 使用isNaN()函数来判断是否为数字:
if( isNaN(s) )
{ alert("no")}
else
{alert("yes")}

在js中,非零为真,零为假


  • 字符串可以连接:
    alert(“abc”+“DEF”)

  • 与用户交互:
    windows.prompt()输入的都是字符串
    var num1=window.prompt("请输入第一个数");
    var num2 =window.prompt("请输入第二个数");
    var res = parseInt(num1) + parseInt(num2);
    alert("结果是"+res);

js使用document.write()进行输出


Js运算符

数字运算符:+ - * / %


使用toFixed()函数来进行小数位数的规定

javascript里的自增自减运算符与C语言相同

++a先加后赋值;a++先赋值后加


逻辑运算符:
&& 与
|| 或
! 非
满足短路表达式
var va1 = 表达式1 && var va2 = 表达式2


位运算:
&与:0&0=0 1&0=0 1&1=1
|或:
^异或


右移运算符:>>
左移运算符:<<
5>>2 = 1
复习原码、反码、补码


JS流程控制

if语句

if (...........)
{...........if   true.......}
else  if (........)
{........if true.}
else
{..........else......}

switch语句

switch(name)
{
case  ".....":1;
......
default:....
}

for循环:
同C语言,不赘述


while循环:
同C语言:


do…while
同C语言


JS可以使用断点


外部文件引入

把代码放到另外一个文件里面:jisuan.js

function jisuan(num1,num2,oper)
{
.............
return .....
}

另一个文件可以使用

<script type="text/javascript" scr="./jisuan.js"></script>
  <script type="text/javascript">
  alert(jusuan(a,b,c))
</script>

函数和调用方式

定义函数:

function test(val)
{
alert(bal);
}
return xxx;
test("haha");

如果我们使用document.write(test),则会显示函数的代码
说明定义一个函数之后,js会在内存里面给函数一个内存位置,实际上是一个内存地址
如果我们使用: var abc = test
使用abc()也可以调用


数组

  • 不同于C语言,js不用定义数组的形式;
var arr = [1,2,3,4,5,6];
var total =0;
for (var i=0;i<arr.length;i++)
{
total +=arr[i]
}
alert(total);

var arry = [1,2,3,4,5,6];
for(var i=0;i<arry.length;i++){    document.write(arry[i]);    document.write("<hr/>");}arry.length
用于显示数组的长度
初始化一个数组:arry = new Arrat(  )
遍历数组:
for (var key in arry)
{
document.write(arry[key])
}

如果遍历溢出,则出现 undefined
js也有python中类似的字符串分割方法:
var str = "192.168.1.1";
var arrt = str.split(".");
alert(arrt);

二维数组

var abc = [[1,2,3],[4,5,6]];
遍历二位数组

for (var i=0;i<abc.length;i++){
var ele = arr[i];
//对ele再次进行遍历
for(var j=0;j<ele.length;j++){
document.write(ele[i]);
}
document.write("<br/>");
}

零基础js面向对象

定义一个类

function Dog(){ }
//初始化一个类的对象
var dog1= new Dog();
dog1.name="名字";
dog1.age=2;
dog1.color="白色";
document.write(dog1.name+" "+dog1.age+" "+dog1.color);
判断对象是否属于类
if(dog1 instanceof Dog){
alert("yes")
}else{
alert("no")
}
使用this给类里面的变量进行初始化
function Dog( ){
this.name = "默认名字"
}
function Person( ){
var name = "默认名字";
var age = 1;
//类里面的函数
this.show = function( )
{
document.write(name +"...." +age);
} }
var p1=new Person( );
p1.name = "小明";
p1.show();

闭包

var a = 90;
function test(){
a = 123;
}
test( );
document.write("a="+a);

此时啊依然是90,由于作用域

function test1()
{
var n = 90; }

对象继承

所谓的对象继承,是指在另一个子对象里面,用一行代码,把父对象所有的内容都包含进去

  • 三种继承方法
    父对象:functiona Stu(name,age)
    子对象:function abc( name,age){
    this.stu=Stu;
    this.stu(name,age);
    }
    或者
    function abc(name,age){
    Stu.call(this,name,age);
    }
    或者
    function abc(name,age){
    Stu.apply(this,[name,age]);
    }

重载

默认情况下,js不支持重载,所以只能对参数进行判断

<script type="text/javascript">
  function Person(){ this.test1=function(){                    if(arguments.lenth==1){
  //有一个参数 
  this.show2(arguments[0]);  } else if(arguments.length==2){
  //有两个参数 
  this.show1(arguments[0],arguments[1]);                    } }
  this.show1=function(a,b){alert("function a b");}
  this.show2=function(a){alert("function a"); } }            var p1 = new Person();p1.test1("a","b");
  //无论传入多少参数,都只默认执行第二个函数  
</script>

覆盖

js在继承时候会有覆盖的功能,原因是其从上到下的执行方式
在书写程序的时候,要把相同名称的函数的书写顺序区分开,相同名称函数的上会覆盖下。

多态

对象、变量在不同情况下的多种状态
js本身无态,所以js支持多态

内部类

内部类包括静态类和动态类
js所有的内部类的父类都是Object,所以他们都有Object的属性和方法
数学函数,
Math.ceil(var number) 向上取整
Math.floor(var number) 向下取整
Math.abs()绝对值
Math.random()随机数,产生大于一小于100的随机数,十六位小数
Math.round()取整,四舍五入

日期类

js里面新建了一个类

var mydate = new Date();
document.write(mydate.tolocaleString());打印当前时间
document.write(mydate.getYear());
document.write(mydate.getMonth()+1);当前月份
document.write(mydate.getSeconds());当前秒
有些时候月份等东西会不正确

String类型

var txt = “haha nihao a world”;
document.write(txt.indexOf(‘ni’)); 返回某个字符串首先出现的位置
document.write(txt.split(“”));以什么进行分割,以数组来接
document.write(txt.substr(3,3));从第几个字符开始,取几个字符
document.write(txt.substring(3,5));从第几个字符开始,取到第7-1个字符
document.write(txt.charAt(3));取出第四个字符


URI 和 Eval

URL统一资源定位符
URI通用资源标识符
使用js来跳转网页。
var name =encodeURI( “abcd cdef”);编码
decodeURI(“”);解码
window.location.href = “url”;跳转函数


eval函数

eval(‘String’)
会把字符串里面的内容当作js代码来进行执行

事件驱动函数
事件源--------事件对象----------事件处理程序
点击事件
事件处理函数

function test(event){
alert("haha")
alert(event.clientX);
}
<input type="button" value="click me" onclick="test(event)"/>

例如,写一个显示鼠标坐标的函数
把函数放到head里面

function showit(event){
x=event.clientX;
y=event.clientY;
document.write("x:"+x+" y:"+y);
}
<body onmousedown="showit(event)">

例如,写一个更换背景的js程序

function mychange(val){
var div1=document.getElementById("div1");
if(val.value=="red"){
div1.style.backgroundColor='red';
} else if(val.value=="black"){
div1.style.backgroundColor='black';
}
}
<div id="div1" style="background-color:red;"></div>
  <input type="button" value="red" onclick="mychange(this)"/>
    <input type="button" value="black" onclick="mychange(this)"/>
  • 设计一个不让用户复制的js代码
    思路:只要用户一点击鼠标右键,程序就进行报错

    我是内容部分,禁止用户进行copy

我们需要注意一下在标签中需要使用return
oncontextmenu: 打开右键标签
onmousedown:让鼠标放下


DOM介绍:

JavaScript的精髓:

内置对象dom,(html dom)
bom—浏览器对象模型
dom是bom的拓展


window中:

event document location history navicator screen


document中:

body styleSheets images links forma all frames
例如,定义一个打印时间的函数

<span id="myspan">???</span>
  <script type="text/javascript">
    var i = 0;
    var myspan = document.getElementById("myspan");
    function abc(){
    var mytime = new Date();
    myspan.innerText=mytime.toLocaleString();
    if(++i==10){
    window.clearInterval(mytime2);
    window.alert("十秒到了!");
    }}
    var mytime2 = window.setIterval("abc( )",1000);
    //每隔一千毫秒(1秒),自动调用函数abc( ),直到唤起clearInterval函数
    </script>

达到无刷页面的方法:
window.setInterval( ):自动调用前一个字符串中的内容,并且在规定的时间调用一次;
window.cleatInterval:清除对应的setInterval里面的东西,使其停止执行;

自动刷新:
三种方法:

  • 1 location.reload();
  • 2 location.replace(“www.baidu.com”);
  • 3 <meta http-equiv="refresh" content="5">

sleep超时操作方法:
sleep(1000).then(function abc());

计时器:

<script>
  function abc(){
  alert("haha");
  }
  var time1 = window.setTimeout("abc( )",3000);
  //setTimeout,三秒弹出,弹出之后就不再工作了
  </script>

对比于setInterval( ),每隔三秒弹出,继续计时

OPEN函数

  • open函数可以打开一个新的窗口

  • open可以让两个页面之间进行互动
    直接附上代码:

<script type="text/javascript">
  //这里是父页面
  var newwindow="";
  function test(){
  newwindow=window.open("new.html");
  //打开新的页面
  }
  function test2(){
  var my_text=document.getElementById("myinfo");
  //找到输入的值
  var new_text=newwindow.document.getEleme**ntById("myinfo");
  //这是newwindow里面的输入的值
  new_text.value=my_text.value;
  //进行赋值
  }
  </script>
    <input onclick="test()" type="submit",value="Open the new console"><br/>
      <input type="text" id="acceptinfo"/><br/>
        <input type="text" id="myinfo"/><br/>
          <input type="submit"onclick="test2()"value="Send the message"/>
            <script>
              //这里是子页面
              function send(){
              var child_text=document.getElementById("myinfo2");
              opener.document.getElementById("acceptinfo").value=child_text.value;
              //opener指打开他的人
              }
              </script>
                <input type="text" id="myinfo"/><br/>
                  <input type="text" id="myinfo2"/><br/>
                    <input type="submit" value="Send to the old console"onclick="send()"/>

history和location对象

  • history对象
    回退操作:
<script>
  function myback( ){
  window.history.go(-1);
  }
</script>
<h1>我是子页面</h1><br/>
<input type="botton" onclick="mu=myback( )" value="返回上一级"/>
  • location对象
定时刷新
<script>
  function myfresh( ){
  window.location.reload( );
  }
  window.setInterval("myfresh( )",5000);
</script>

还可以用window.location.href="http://www.baidu.com";

event方法

  • 静态绑定
    直接写入进行使用
  • 动态绑定
    通过一个方法给另一个对象赋予方法
<script>
  //jquery方法,通过$(id)直接传入id
  function $(id){
  return document.getElementById(id);
  }
  function test1(){
  alert("test1");
  $('bt2').onclick=test2;
  //等于document.getElementById('bt2').onclick=test2;
  }
  //在这边触发了方法1的同时,bt2标签也被赋予了方法
  function test2(){
  alert("test2");
  }
  //只有在我们点击并且触发了方法一的时候,方法二才会被赋予
  //可以作为一个装弹游戏
</script>
<input type="button" id="bt1" onclick="test1()"value="测试1"/>
<input type="button" id="bt2" value="测试2"/>

  • 举个例子,同意条款才给你点击
<script>
  var i = 10;
  function counttime(){
  var btn1 = document.getElementById("bt1");
  //每一次都获取这个标签,并且赋值给btn1
  i--;
  btn1.value="同意 "+i;
  if(i==0){
  btn1.value="同意";
  btn1.disabled=false;
  window.clearInterval(mytimer);
  //停止调用
  }
  }
  function ps1(){
  window.location.href="https://www.baidu.com";
  }
  var mytimer=window.setInterval("counttime()",1000);
  //每一秒自动调用这个函数
</script>
<p>我同意上述条款</p>
<input type="button" id="bt1" value="我同意 10" disabled="true" onclick="ps1()"/>
<!--通过disabled属性来定义按钮是否可以被点击-->

document对象

通过各种方法来选择对象:

<head>
    <meta charset="UTF-8">
      <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>Time</title>
        <script>
          function test1(){
          //这是第一种方法
          var a1=document.getElementById("a1");
          a1.innerText="修改到了百度";//修改里面的文本
          a1.href="http://www.baidu.com";//修改里面的链接
          }
          function test2(){
          //这是第二种方法
          var hobby=document.getElementsByName("hobby");
          //通过这个方法,取出多个标签,并且通过hobby数组进行索引
          for(var i=0;i<hobby.length;i++){
          if(hobby[i].checked){
          //是否选中
          alert("你的爱好是"+hobby[i].value);
          //弹窗提示出hobby标签的值有多少
          }
          }
          }
          function test3(){
          //这是第三种方法
          var inputs=document.getElementsByTagName("input");
          alert(inputs.length);//输出input标签有多少个
          }
        </script>
      </head>
      <body>
      <a id="a1" href="http://www.sina.com">连接到sina</a><br/>
    <a id="a2" href="http://www.sohu.com">连接到sohu</a><br/>
  <a id="a3" href="http://www.baidu.com">连接到baidu</a><br/>
  <input type="button" value="修改到百度" onclick="test1()"/><br/>
  请选择你的爱好:
    <input type="checkbox" name="hobby" value="旅游">旅游
      <input type="checkbox" name="hobby" value="音乐">音乐
        <input type="checkbox" name="hobby" value="体育">体育
          <input type="checkbox" name="hobby" value="电影">电影
          <input type="button" value="看看你的爱好" onclick="test2()"/><br/>
          <input type="button" value="通过tagname来获取元素" onclick="test3()"/><br/>
        </body>

元素动态创建

四种方法:

  • createElement 创建元素
  • appendChild 创建子节点
  • removeChild 删除指定的节点
  • parentNode 返回父节点
<body>
  <script>
    function test1(){
    var myhref=document.createElement("a");//创建一个a标签
    var div1=document.getElementById("div1");
    myhref.innerText="我是一个链接";
    myhref.href="http://www.qq.com";
    myhref.id="myhref";
    div1.appendChild(myhref);
    //把刚刚创建的节点拓展到div1底下
    }
    function test2(){
    var div1=document.getElementById("div1");
    var node=document.getElementById("myhref");
    node.parentNode.removeChild(node);//删除节点
    //也可以写成div1.removeChild(node);
    }
  </script>
  <input type="button" onclick="test1()"value="创建子标签"/><br/>
  <input type="button" onclick="test2()"value="删除子标签"/><br/>
<div id="div1"style="background-color:blue;">div1</div>
</body>

posted on 2025-10-14 22:29  slgkaifa  阅读(8)  评论(0)    收藏  举报

导航