javascript

①1.CSS

1.1语法

  • 选择器和声明块组成:

     p {
       color: red;
       text-align: center;
     }
    • p 是 CSS 中的选择器(它指向要设置样式的 HTML 元素:<p>)。

    • color 是属性,red 是属性值

    • text-align 是属性,center 是属性值

②1.2选择器

简单选择器

  • id选择器

    •  <head>
       <style>
       #para1 {
         text-align: center;
         color: red;
       }
       </style>
       </head>
       <body>
       ​
       <p id="para1">Hello World!</p>
       <p>本段不受样式的影响。</p>
       ​
       </body>
  • 类选择器

    •  <head>
       <style>
       .center {
         text-align: center;
         color: red;
       }
       </style>
       </head>
       <body>
       ​
       <h1 class="center">居中的红色标题</h1>
       <p class="center">居中的红色段落。</p> 
       ​
       </body>
    •  <head>
       <style>
       p.center {
         text-align: center;
         color: red;
       }
       </style>
       </head>
       <body>
       ​
       <h1 class="center">这个标题不受影响</h1>
       <p class="center">这个段落将是红色并居中对齐的。</p> 
       ​
       </body>
    •  <head>
       <style>
       p.center {
         text-align: center;
         color: red;
       }
       ​
       p.large {
         font-size: 300%;
       }
       </style>
       </head>
       <body>
       ​
       <h1 class="center">这个标题不受影响</h1>
       <p class="center">本段将是红色并居中对齐。</p>
       <p class="center large">本段将是红色、居中对齐,并使用大字体。</p> 
       ​
       </body>
  • 通用选择器

    •  <head>
       <style>
       * {
         text-align: center;
         color: blue;
       }
       </style>
       </head>
       <body>
       ​
       <h1>Hello world!</h1>
       ​
       <p>页面上的每个元素都会受到样式的影响。</p>
       <p id="para1">我也是!</p>
       <p>还有我!</p>
       ​
  • 分组选择器

    •  h1 {
         text-align: center;
         color: red;
       }
       ​
       h2 {
         text-align: center;
         color: red;
       }
       ​
       p {
         text-align: center;
         color: red;
       }

组合器选择器

  •  后代选择器 (空格)
     选择 <div> 元素内的所有 <p> 元素:
     div p {
       background-color: yellow;
     }
  •  子选择器 (>)
     <div> 元素子元素的所有 <p> 元素:
     div > p {
       background-color: yellow;
     }
  •  相邻兄弟选择器
     选择紧随 <div> 元素之后的所有 <p> 元素:
     div + p {
       background-color: yellow;
     }
  •  通用兄弟选择器
     div ~ p {
       background-color: yellow;
     }

伪类选择器

  • 伪类用于定义元素的特殊状态。

    例如,它可以用于:

    • 设置鼠标悬停在元素上时的样式

    • 为已访问和未访问链接设置不同的样式

    • 设置元素获得焦点时的样式

  • 锚伪类

    •  /* 未访问的链接 */
       a:link {
         color: #FF0000;
       }
       ​
       /* 已访问的链接 */
       a:visited {
         color: #00FF00;
       }
       ​
       /* 鼠标悬停链接 */
       a:hover {
         color: #FF00FF;
       }
       ​
       /* 已选择的链接 */
       a:active {
         color: #0000FF;
       }
  • 伪类和CSS类

    • 伪类可以与 CSS 类结合使用:当您将鼠标悬停在例子中的链接上时,它会改变颜色;

  • 悬停在 <div> 上

    •  p {
         display: none;
         background-color: yellow;
         padding: 20px;
       }
       ​
       div:hover p {
         display: block;
       }
  • CSS - :first-child 伪类

    •  cp:first-child {
         color: blue;
       }

伪元素选择器

  •  p::first-line {
       color: #ff0000;
       font-variant: small-caps;
     }

属性选择器

  • CSS [attribute] 选择器

    • [attribute] 选择器用于选取带有指定属性的元素。

    • 下例选择所有带有 target 属性的 <a> 元素;

    •  a[target] {
         background-color: yellow;
       }
    •  a[target="_blank"] { 
         background-color: yellow;
       }
    •  [title~="flower"] {
         border: 5px solid yellow;
       }
    •  [class|="top"] {
         background: yellow;
       }
    •  [class$="test"] {
         background: yellow;
       }
    •  [class^="top"] {
         background: yellow;
       }
    •  input[type="text"] {
         width: 150px;
         display: block;
         margin-bottom: 10px;
         background-color: yellow;
       }
       ​
       input[type="button"] {
         width: 120px;
         margin-left: 35px;
         display: block;
       }

③1.3添加CSS

  • 外部CSS

    •  <!DOCTYPE html>
       <html>
       <head>
       <link rel="stylesheet" type="text/css" href="mystyle.css">
       </head>
       <body>
       ​
       <h1>This is a heading</h1>
       <p>This is a paragraph.</p>
       ​
       </body>
       </html>
    •  "mystyle.css"
       body {
         background-color: lightblue;
       }
       ​
       h1 {
         color: navy;
         margin-left: 20px;
       }
  • 内部css

    •  <!DOCTYPE html>
       <html>
       <head>
       <style>
       body {
         background-color: linen;
       }
       ​
       h1 {
         color: maroon;
         margin-left: 40px;
       } 
       </style>
       </head>
       <body>
       ​
       <h1>This is a heading</h1>
       <p>This is a paragraph.</p>
       ​
       </body>
       </html>
  • 行内css(不推荐使用)

    •  <!DOCTYPE html>
       <html>
       <body>
       ​
       <h1 style="color:blue;text-align:center;">This is a heading</h1>
       <p style="color:red;">This is a paragraph.</p>
       ​
       </body>
       </html>
  • 因此,行内样式具有最高优先级,并且将覆盖外部和内部样式以及浏览器默认样式。

    • 行内样式(在 HTML 元素中)

    • 外部和内部样式表(在 head 部分)

    • 浏览器默认样式

  •  颜色:
     <h1 style="color:Tomato;">China</h1>
  •  背景:
     div {
       background-color: green;
       opacity: 0.3;
     }
  •  body {
       background-image: url("bgdesert.jpg");
     }
  •  边框
     p.three {
       border-style: solid;
       border-width: 25px 10px 4px 35px; /* 上边框 25px,右边框 10px,下边框 4px,左边框 35px */
     }
  •  设置 <div> 元素的高度和宽度:
     div {
       height: 200px;
       width: 50%;
       background-color: powderblue;
     }
  •  文本属性:
     body {
       background-color: lightgrey;
       color: blue;
     }
     ​
     h1 {
       background-color: black;
       color: white;
     }
  •  块级元素总是从新行开始,并占据可用的全部宽度(尽可能向左和向右伸展)。
     块级元素的一些例子:
     <div>
     <h1> - <h6>
     <p>
     <form>
     <header>
     <footer>
     <section>
     内联元素不从新行开始,仅占用所需的宽度。
     这是段落中的行内 <span> 元素。
     行内元素的一些例子:
     <span>
     <a>
     <img>
     ​
     h1.hidden {
       display: none;
     }
     h1.hidden {
       visibility: hidden;
     }
  •  div.ex1 {
       width: 500px;
       margin: auto;
       border: 3px solid #73AD21;
     }
     ​
     div.ex2 {
       max-width: 500px;
       margin: auto;
       border: 3px solid #73AD21;
     }
  •  css布局-浮动和清除
     img {
       float: right;
     }

①2.jQuery

  • $

②2.1安装

③2.2事件

  • jQuery 是为事件处理特别设计的。

  • 通常会把 jQuery 代码放到 <head>部分的事件处理方法中:

  • 由于 jQuery 是为处理 HTML 事件而特别设计的,那么当您遵循以下原则时,您的代码会更恰当且更易维护:

    • 把所有 jQuery 代码置于事件处理函数中

    • 把所有事件处理函数置于文档就绪事件处理器中

    • 把 jQuery 代码置于单独的 .js 文件中

    • 如果存在名称冲突,则重命名 jQuery 库

  •  <html>
     <head>
     <script type="text/javascript" src="jquery.js"></script>
     <script type="text/javascript">
     $(document).ready(function(){
       $("button").click(function(){
         $("p").hide();
       });
     });
     </script>
     </head>
     ​
     <body>
     <h2>This is a heading</h2>
     <p>This is a paragraph.</p>
     <p>This is another paragraph.</p>
     <button>Click me</button>
     </body>
     ​
     </html>

单独文件中的函数

  •  <head>
     <script type="text/javascript" src="jquery.js"></script>
     <script type="text/javascript" src="my_jquery_functions.js"></script>
     </head>

jQuery 名称冲突

  •  <!DOCTYPE html>
     <html>
     <head>
     <script src="/jquery/jquery-1.11.1.min.js"></script>
     <script>
     $.noConflict();
     jQuery(document).ready(function(){
       jQuery("button").click(function(){
         jQuery("p").text("jQuery 仍在运行!");
       });
     });
     </script>
     </head>
     ​
     <body>
     <p>这是一个段落。</p>
     <button>测试 jQuery</button>
     </body>
     </html>
     ​

④2.3效果

隐藏、显示

  •  $("#hide").click(function(){
       $("p").hide();
     });
     ​
     $("#show").click(function(){
       $("p").show();
     });

切换

  •  $("button").click(function(){
       $("p").toggle();
     });

淡入/淡出

  •  淡入
     $("button").click(function(){
       $("#div1").fadeIn();
       $("#div2").fadeIn("slow");
       $("#div3").fadeIn(3000);
     });
  •  淡出
     $("button").click(function(){
       $("#div1").fadeOut();
       $("#div2").fadeOut("slow");
       $("#div3").fadeOut(3000);
     });

Chaining

  • Chaining 允许我们在一条语句中允许多个 jQuery 方法(在相同的元素上)。

  •  $("#p1").css("color","red").slideUp(2000).slideDown(2000);

⑤2.4jquery HTML

  • jQuery 拥有可操作 HTML 元素(内容)和属性的强大方法。

获取DOM

  • 三个简单实用的用于 DOM 操作的 jQuery 方法:

    • text() - 设置或返回所选元素的文本内容

    • html() - 设置或返回所选元素的内容(包括 HTML 标记)

    • val() - 设置或返回表单字段的值

设置

  • 情况1:设置值

  • 方法1:我们将使用前一章中的三个相同的方法来设置内容:

    • text() - 设置或返回所选元素的文本内容

    • html() - 设置或返回所选元素的内容(包括 HTML 标记)

    • val() - 设置或返回表单字段的值

    •  $("#btn1").click(function(){
         $("#test1").text("Hello world!");
       });
       $("#btn2").click(function(){
         $("#test2").html("<b>Hello world!</b>");
       });
       $("#btn3").click(function(){
         $("#test3").val("Dolly Duck");
       });
  • 方法2:text()、html() 以及 val() 的回调函数

    •  $("#btn1").click(function(){
         $("#test1").text(function(i,origText){
           return "Old text: " + origText + " New text: Hello world!
           (index: " + i + ")";
         });
       });
       ​
       $("#btn2").click(function(){
         $("#test2").html(function(i,origText){
           return "Old html: " + origText + " New html: Hello <b>world!</b>
           (index: " + i + ")";
         });
       });
  • 情况2:设置属性

  • 方法1:

    •  $("button").click(function(){
         $("#w3s").attr("href","http://www.w3school.com.cn/jquery");
       });
  • 方法2:回调函数

    •  $("button").click(function(){
         $("#w3s").attr("href", function(i,origValue){
           return origValue + "/jquery";
         });
       });

添加元素

  • 通过 jQuery,可以很容易地添加新元素/内容。

  • 我们将学习用于添加新内容的四个 jQuery 方法:

    • append() - 在被选元素的结尾插入内容

    • prepend() - 在被选元素的开头插入内容

    • after() - 在被选元素之后插入内容

    • before() - 在被选元素之前插入内容

  •  $("p").append("Some appended text.");
  •  $("p").prepend("Some prepended text.");
  •  function appendText()
     {
     var txt1="<p>Text.</p>";               // 以 HTML 创建新元素
     var txt2=$("<p></p>").text("Text.");   // 以 jQuery 创建新元素
     var txt3=document.createElement("p");  // 以 DOM 创建新元素
     txt3.innerHTML="Text.";
     $("p").append(txt1,txt2,txt3);         // 追加新元素
     }
  •  function afterText()
     {
     var txt1="<b>I </b>";                    // 以 HTML 创建新元素
     var txt2=$("<i></i>").text("love ");     // 通过 jQuery 创建新元素
     var txt3=document.createElement("big");  // 通过 DOM 创建新元素
     txt3.innerHTML="jQuery!";
     $("img").after(txt1,txt2,txt3);          // 在 img 之后插入新元素
     }

删除元素/内容

  • 如需删除元素和内容,一般可使用以下两个 jQuery 方法:

    • remove() - 删除被选元素(及其子元素)

    • empty() - 从被选元素中删除子元素

  •  $("#div1").remove();
  •  $("#div1").empty();
  •  $("p").remove(".italic");

获取并设置CSS类

  • 通过 jQuery,可以很容易地对 CSS 元素进行操作。切换类

  • jQuery 拥有若干进行 CSS 操作的方法。我们将学习下面这些:

    • addClass() - 向被选元素添加一个或多个类

    • removeClass() - 从被选元素删除一个或多个类

    • toggleClass() - 对被选元素进行添加/删除类的切换操作

    • css() - 设置或返回样式属性

  •  .important
     {
     font-weight:bold;
     font-size:xx-large;
     }
     ​
     .blue
     {
     color:blue;
     }
     ​
     $("button").click(function(){
       $("h1,h2,p").addClass("blue");
       $("div").addClass("important");
     });
    •  可以在 addClass() 方法中规定多个类:
       $("button").click(function(){
         $("#div1").addClass("important blue");
       });
  •  $("button").click(function(){
       $("h1,h2,p").removeClass("blue");
     });
  •  $("button").click(function(){
       $("h1,h2,p").toggleClass("blue");
     });

css()方法

  • css() 方法设置或返回被选元素的一个或多个样式属性。

    •  $("p").css("background-color","yellow");
    •  $("p").css({"background-color":"yellow","font-size":"200%"});

⑥2.5jquery遍历(DOM遍历)

向上遍历

  • 这些 jQuery 方法很有用,它们用于向上遍历 DOM 树:

    • parent()

    • parents()

    • parentsUntil()

  •  $(document).ready(function(){
       $("span").parent();
     });
  •  $(document).ready(function(){
       $("span").parents();
     });
  •  $(document).ready(function(){
       $("span").parentsUntil("div");
     });

向下遍历

  • 下面是两个用于向下遍历 DOM 树的 jQuery 方法:

    • children()

    • find()

  •  $(document).ready(function(){
       $("div").children();
     });
    • 可以使用可选参数来过滤对子元素的搜索。

    •  $(document).ready(function(){
         $("div").children("p.1");
       });
  •  $(document).ready(function(){
       $("div").find("span");
     });
    •  $(document).ready(function(){
         $("div").find("*");
       });

同胞

  • 同胞拥有相同的父元素。通过 jQuery,您能够在 DOM 树中遍历元素的同胞元素。

  • 有许多有用的方法让我们在 DOM 树进行水平遍历:

    • siblings()

    • next()

    • nextAll()

    • nextUntil()

    • prev()

    • prevAll()

    • prevUntil()

  •  $(document).ready(function(){
       $("h2").siblings();
     });
    • 过滤

    •  $(document).ready(function(){
         $("h2").siblings("p");
       });
  •  $(document).ready(function(){
       $("h2").next();
     });
  •  $(document).ready(function(){
       $("h2").nextAll();
     });
  •  $(document).ready(function(){
       $("h2").nextUntil("h6");
     });

过滤

  • 缩写搜索元素的范围

    • 最基本的过滤方法是:first(), last() 和 eq(),它们允许您基于其在一组元素中的位置来选择一个特定的元素

    • filter() 和 not() 允许您选取匹配或不匹配某项指定标准的元素。

  •  $(document).ready(function(){
       $("div p").first();
     });
  •  $(document).ready(function(){
       $("div p").last();
     });
  •  $(document).ready(function(){
       $("p").eq(1);
     });
  •  $(document).ready(function(){
       $("p").filter(".intro");
     });
  •  $(document).ready(function(){
       $("p").not(".intro");
     });

⑦2.6jQuery-AJAX

AJAX load()方法

  • load() 方法从服务器加载数据,并把返回的数据放入被选元素中。

    •  $(selector).load(URL,data,callback);
    •  <!DOCTYPE html>
       <html>
       <head>
       <script src="/jquery/jquery-1.11.1.min.js">
       </script>
       <script>
       $(document).ready(function(){
         $("#btn1").click(function(){
           $('#test').load('/example/jquery/demo_test.txt');
         })
       })
       </script>
       </head>
       ​
       <body>
       ​
       <h3 id="test">请点击下面的按钮,通过 jQuery AJAX 改变这段文本。</h3>
       <button id="btn1" type="button">获得外部的内容</button>
       ​
       </body>
       </html>
  • 回调函数

    •  $("button").click(function(){
         $("#div1").load("demo_test.txt",function(responseTxt,statusTxt,xhr){
           if(statusTxt=="success")
             alert("外部内容加载成功!");
           if(statusTxt=="error")
             alert("Error: "+xhr.status+": "+xhr.statusText);
         });
       });

AJAX get() 和 post() 方法

  • jQuery get() 和 post() 方法用于通过 HTTP GET 或 POST 请求从服务器请求数据。

  • $.get() 方法通过 HTTP GET 请求从服务器上请求数据

    •  $.get(URL,callback);
    •  $("button").click(function(){
         $.get("demo_test.asp",function(data,status){
           alert("Data: " + data + "\nStatus: " + status);
         });
       });
  •  $.post(URL,data,callback);
    •  $("button").click(function(){
         $.post("demo_test_post.asp",
         {
           name:"Donald Duck",
           city:"Duckburg"
         },
         function(data,status){
           alert("Data: " + data + "\nStatus: " + status);
         });
       });

①JS教程

1.where:

  • 必须放下:<script>

    • 可以<body><head>

    • 外部:可以<src:>

2.输出(4)

  • 使用 window.alert() 写入警告框

  • 使用 document.write() 写入 HTML 输出

  • 使用 innerHTML 写入 HTML 元素

  • 使用 console.log() 写入浏览器控制台

3.数据类型(5)

  • 字符串值,数字,布尔,对象,函数。

0. 字符串值

  • 字符串的转义

  • 方法

1. 数字

2.对象

  • var person = {
      firstName: "Bill",
      lastName : "Gates",
      id       : 678,
      fullName : function() {
        return this.firstName + " " + this.lastName;
      }
    };
  • var person = {"firstName":"Bill", lastName:"Gates", "age":62, eyeColor:"blue"};
  • 1.1对象的访问:

    • objectName.propertyName     person.lastName;

      或者

      objectName["propertyName"]   person["lastName"];
  • 2.数组

  • 2.1数组的访问

    • var cars = ["Saab", "Volvo", "BMW"];
      document.getElementById("demo").innerHTML = cars[0]; 
  • 2.2方法:

  • 2.3 数组排序

    • sort()

  • 2.4数组迭代

    • foreach

    • map

    • filter

    • reduce

    • find

3. 类型转换

  • String(100 + 23)

4.对象类型(3)

1. 对象

2. 日期

  • 日期格式

  • 获取方法

  • 设置方法

2.1 数学

2.2 随机

3. 数组

5. this(3)

  • 方法

    • 1.对象方法绑定

      • var person = {
          firstName: "Bill",
          lastName : "Gates",
          id     : 678,
          fullName : function() {
            return this;
          }
        };
      • [object Object]

  • 函数

    • 1.对象方法绑定

      • function myFunction() {
          return this;
        }
      • [object Window]

    • 2.显式函数绑定

      • var person1 = {
          fullName: function() {
            return this.firstName + " " + this.lastName;
          }
        }
        var person2 = {
          firstName:"Bill",
          lastName: "Gates",
        }
        person1.fullName.call(person2);  // 会返回 "Bill Gates"
  • 事件

    • <button οnclick="this.style.display='none'">
        点击来删除我!
      </button>

6. JSON

  • JSON数据:

    • JSON 名称需要双引号。JavaScript 名称不需要。

    • "firstName":"Bill"
  • JSON对象

    • JSON 对象是在花括号内书写的。

    • 类似 JavaScript,对象能够包含多个名称/值对:

      {"firstName":"Bill", "lastName":"Gates"} 
  • JSON数组

    • JSON 数组在方括号中书写。

    • 类似 JavaScript,数组能够包含对象:

    • "employees":[
          {"firstName":"Bill", "lastName":"Gates"}, 
          {"firstName":"Steve", "lastName":"Jobs"}, 
          {"firstName":"Alan", "lastName":"Turing"}
      ]
  • JSON文本转javascript对象

    • 首先,创建包含 JSON 语法的 JavaScript 字符串:

      var text = '{ "employees" : [' +
      '{ "firstName":"Bill" , "lastName":"Gates" },' +
      '{ "firstName":"Steve" , "lastName":"Jobs" },' +
      '{ "firstName":"Alan" , "lastName":"Turing" } ]}';
var text = '{ "employees" : [' +
'{ "firstName":"Bill" , "lastName":"Gates" },' +
'{ "firstName":"Steve" , "lastName":"Jobs" },' +
'{ "firstName":"Alan" , "lastName":"Turing" } ]}';

'+'单独添加

②JS对象

  • 1.变量与对象

    • var person = {firstName:"Bill", lastName:"Gates", age:62, eyeColor:"blue"}
      var x = person;// 这不会创建 person 的副本
      x.age = 10;           // 这将同时改变 both x.age 和 person.age
  • 2.对象属性

    • 比如firstName

    • 属性的访问

      objectName.property           // person.age
      objectName["property"]       // person["age"]
      objectName[expression]       // x = "age"; person[x]
    • var person = {fname:"Bill", lname:"Gates", age:62}; 
      
      for (x in person) {
          txt += person[x];
      }
    • 添加新属性

      • person.nationality = "English";删除属性
    • 删除属性

      • var person = {firstName:"Bill", lastName:"Gates", age:62, eyeColor:"blue"};
        delete person.age;   // 或 delete person["age"];
  • 3.对象方法

    • 方法1:请使用如下语法创建对象方法:

      methodName : function() { 代码行 }

      请通过如下语法来访问对象方法:

      objectName.methodName()
    • 方法2:添加新方法:

      function person(firstName, lastName, age, eyeColor) {
          this.firstName = firstName;  
          this.lastName = lastName;
          this.age = age;
          this.eyeColor = eyeColor;
          this.changeName = function (name) {
              this.lastName = name;
          };
      }

      changeName() 函数 name 的值赋给了 person 的 lastName 属性。

      现在您可以尝试:

      myMother.changeName("Jobs");
    • 对象访问器

      • JavaScript 函数还是 Getter?

        var person = {
          firstName: "Bill",
          lastName : "Gates",
          get fullName() {
            return this.firstName + " " + this.lastName;
          }
        };
        
        // 使用 getter 来显示来自对象的数据:
        document.getElementById("demo").innerHTML = person.fullName;
  • 4.创建对象

    • var person = {firstName:"Bill", lastName:"Gates", age:62, eyeColor:"blue"};
    • 方式2:

  • 5.对象原型

    • 所有 JavaScript 对象都从原型继承属性和方法。

    • 方式1:它们只创建单一对象。
      function Person(first, last, age, eyecolor) {
          this.firstName = first;
          this.lastName = last;
          this.age = age;
          this.eyeColor = eyecolor;
      }
      Person.prototype.name = function() {
          return this.firstName + " " + this.lastName;
      };
    • 方式2:有时我们需要创建相同“类型”的许多对象的“蓝图”。创建一种“对象类型”的方法,是使用对象构造器函数。
      <script>
      // Person 对象的构造器函数
      function Person(first, last, age, eye) {
        this.firstName = first;
        this.lastName = last;
        this.age = age;
        this.eyeColor = eye;
      }
      
      // 创建 Person 对象
      var myFriend = new Person("Bill", "Gates", 62, "blue");
      
      // 显示年龄
      document.getElementById("demo").innerHTML =
      "My friend is " + myFriend.age + "."; 
      </script>

③JS函数

1.定义

  • 1.函数声明

function myFunction(a, b) {
     return a * b;
}
  • 2.函数表达式

    • 在变量中保存函数表达式之后,此变量可用作函数:

var x = function (a, b) {return a * b};
var z = x(4, 3);

2.使用

  • “提升”(hoisting)

  • 自调用函数

  • 箭头函数

    • // ES5
      var x = function(x, y) {
        return x * y;
      }
      
      // ES6
      const x = (x, y) => x * y;

3.call()

  • call() 方法可接受参数:
    var person = {
      fullName: function(city, country) {
        return this.firstName + " " + this.lastName + "," + city + "," + country;
      }
    }
    var person1 = {
      firstName:"Bill",
      lastName: "Gates"
    }
    person.fullName.call(person1, "Seattle", "USA");

4.apply()

  • all() 和 apply() 之间的区别:不同之处是:

    call() 方法分别接受参数。

    apply() 方法接受数组形式的参数。

    如果要使用数组而不是参数列表,则 apply() 方法非常方便。

    • var person = {
        fullName: function(city, country) {
          return this.firstName + " " + this.lastName + "," + city + "," + country;
        }
      }
      var person1 = {
        firstName:"John",
        lastName: "Doe"
      }
      person.fullName.apply(person1, ["Oslo", "Norway"]);
  • 在数组上模拟 max 方法

    • Math.max.apply(null, [1,2,3]); // 也会返回 3
    • Math.max.apply(Math, [1,2,3]); // 也会返回 3
    • Math.max.apply(" ", [1,2,3]); // 也会返回 3

5.闭包

  • // 递增计数器的函数
    function add() {
      var counter = 0; 
      counter += 1;
      return counter;
    }
    
    // 调用三次 add()
    add();
    add();
    add();
    
    //此时计数器应该是 3。但它是 1。
  • var add = (function () {
        var counter = 0;
        return function () {return counter += 1;}
    })();
    
    add();
    add();
    add();
    
    // 计数器目前是 3 
    
    //只调用(function(){...})一次:自调用函数
    //var add=function () {return counter += 1;}:函数定义--函数表达式
    //counter:自动全局

5.1涉及:js作用域

  • 自动全局:

    如果您为尚未声明的变量赋值,此变量会自动成为全局变量。

    这段代码将声明一个全局变量 carName,即使在函数内进行了赋值。

myFunction();
// 此处的代码能够使用 carName 变量
function myFunction() {
    carName = "porsche";
}

5.2涉及:函数定义:自调用函数

④JS HTML DOM

  • HTML DOM 是关于如何获取、更改、添加或删除 HTML 元素的标准

1.方法,2.属性

<html>
<body>

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML = "Hello World!";
</script>

</body>
</html>

在上面的例子中,getElementById 是方法,而 innerHTML 是属性

3.文档对象document

  • 查找HTML元素:element

    • 通过元素 id 来查找元素:element=document.getElementById(id)

    • 通过标签名来查找元素:element=document.getElementsByTagName(name)

    • 通过类名来查找元素:element=document.getElementsByClassName(name)

  • 改变HTML元素:

    • 改变元素的 inner HTML:element.innerHTML

    • 改变 HTML 元素的属性值:element.attribute = new value

    • 改变 HTML 元素的属性值:element.setAttribute(attribute, value)

    • 改变 HTML 元素的样式:element.style.property = new style

      • CSS

      • <html>
        <body>
        
        <p id="p2">Hello World!</p>
        
        <script>
        document.getElementById("p2").style.color = "blue";
        </script>
        
        <p>上面的段落已被脚本改变。</p>
        
        </body>
        </html>
      • <!DOCTYPE html>
        <html>
        <body>
        
        <h1 id="id1">我的标题 1</h1>
        
        <button type="button" οnclick="document.getElementById('id1').style.color = 'red'">
        点击我!
        </button>
        
        </body>
        </html>
  • 添加和删除元素

    • 创建HTML元素:document.createElement(element)

    • 删除:document.removeChild(element)

    • 添加:document.appendChild(element)

    • 替换:document.replaceChild(element)

  • 添加事件处理程序

    • 向 onclick 事件添加事件处理程序:document.getElementById(id).onclick = function(){code}

  • 查找HTML对象

4. DOM事件

onclick事件:

  • 对事件作出反应

<!DOCTYPE html>
<html>
<body>
<h1 οnclick="this.innerHTML = 'Hello!'">点击此文本!</h1>
</body>
</html> 
  • 从事件处理程序调用函数:

<!DOCTYPE html>
<html>
<body>
<h1 οnclick="changeText(this)">点击此文本!</h1>
<script>
function changeText(id) { 
    id.innerHTML = "Hello:)";
}
</script>
</body>
</html> 
  • HTML事件属性:

<button οnclick="displayDate()">试一试</button>
  • 向 HTML 元素分配事件:

<script>
document.getElementById("myBtn").onclick = displayDate;
</script> 

onload事件:

onchange事件:

  • 事件经常与输入字段验证结合使用。

<input type="text" id="fname" οnchange="upperCase()">

onmouseover 和 onmouseout 事件

<div οnmοuseοver="mOver(this)" οnmοuseοut="mOut(this)" 
style="background-color:#D94A38;width:120px;height:20px;padding:40px;">
请把鼠标移上来</div>

<script>
function mOver(obj) {
  obj.innerHTML = "谢谢您"
}

function mOut(obj) {
  obj.innerHTML = "请把鼠标移上来"
}
</script>

5. DOM事件监听器

  • addEventListener()方法

document.getElementById("myBtn").addEventListener("click", displayDate);
  • 语法:element.addEventListener(event, function, useCapture);

  • 向相同元素添加多个事件处理程序

    • element.addEventListener("click", myFunction);
      element.addEventListener("click", mySecondFunction);
    • element.addEventListener("mouseover", myFunction);
      element.addEventListener("click", mySecondFunction);
      element.addEventListener("mouseout", myThirdFunction);
  • 事件冒泡还是事件捕获?

  • removeEventListener() 方法

6.DOM导航

<html>

   <head>
       <title>DOM 教程</title>
   </head>

  <body>
       <h1>DOM 第一课</h1>
       <p>Hello world!</p>
   </body>

</html> 
从以上的 HTML 中您能读到以下信息:

<html> 是根节点
<html> 没有父
<html> 是 <head> 和 <body> 的父
<head> 是 <html> 的第一个子
<body> 是 <html> 的最后一个子
同时:

<head> 有一个子:<title>
<title> 有一个子(文本节点):"DOM 教程"
<body> 有两个子:<h1> 和 <p>
<h1> 有一个子:"DOM 第一课"
<p> 有一个子:"Hello world!"
<h1> 和 <p> 是同胞
  • 在节点之间导航

  • 子节点和节点值

  • 文本节点:InnerHTML

7.DOM节点

⑤JS Browser BOM

1.JS Location

  • window.location.assign() 方法加载新文档。

  • <html>
    <head>
    <script>
    function newDoc() {
        window.location.assign("https://www.w3school.com.cn")
     }
    </script>
    </head>
    <body>
    
    <input type="button" value="Load new document" οnclick="newDoc()">
    
    </body>
    </html> 

2. Timing事件

  • setTimeout(function, milliseconds)

  • 在等待指定的毫秒数后执行函数。

  • setInterval(function, milliseconds)

    • 等同于 setTimeout(),但持续重复执行该函数。

  • 如何停止执行?

    • myVar = setInterval(function, milliseconds);
      clearInterval(myVar);

⑥JS JSON

1.语法规则

  • JSON 名称需要双引号。JavaScript 名称不需要。

  • JSON对象:

    • JSON 名称需要双引号 : {"firstName":"Bill", "lastName":"Gates"} 
    • JavaScript对象 名称不需要: var car = {type:"porsche", model:"911", color:"white"};
      • JavaScript变量 var car = "porsche";
  • JSON数组:

    • {
      "employees":[
          {"firstName":"Bill", "lastName":"Gates"}, 
          {"firstName":"Steve", "lastName":"Jobs"},
          {"firstName":"Alan", "lastName":"Turing"}
      ]
      }
  • 语法规则

    • 数据是名称/值对

    • 数据由逗号分隔

    • 花括号保存对象

    • 方括号保存数组

2.交换数据: 发送数据,接收数据

  • json格式评估为javascript对象

    • JSON 格式在语法上与创建 JavaScript 对象的代码相同。

    • 由于这种相似性,JavaScript 程序可以很容易地将 JSON 数据转换成本地的 JavaScript 对象。

    • JSON.parse()
  • 如果您的数据存储在 JavaScript 对象中,您可以把该对象转换为 JSON,然后将其发送到服务器。
    var myObj = { name:"Bill Gates",  age:62, city:"Seattle" };
    var myJSON =  JSON.stringify(myObj);
    window.location = "demo_json.php?x=" + myJSON;
  • 如果您以 JSON 格式接收到数据,您能够将其转换为 JavaScript 对象:
    var myJSON = '{ "name":"Bill Gates",  "age":62, "city":"Seattle" }';
    var myObj =  JSON.parse(myJSON);
    document.getElementById("demo").innerHTML = myObj.name;

3. 存储数据

  • JSON 让 JavaScript 对象存储为文本。

  • //存储数据:
    myObj = { name:"Bill Gates",  age:62, city:"Seattle" };
    myJSON =  JSON.stringify(myObj);
    localStorage.setItem("testJSON", myJSON);
    
    //接收数据:
    text = localStorage.getItem("testJSON");
    obj =  JSON.parse(text);
    document.getElementById("demo").innerHTML = obj.name;

4. JSON使用JavaScript语法

5. 数据类型

在 JSON 中,值必须是以下数据类型之一:

  • 字符串 { "name":"John" }
  • 数字 { "age":30 }
  • 对象(JSON 对象){
    "employee":{ "name":"Bill Gates", "age":62, "city":"Seattle" }
    }
  • 数组
    {
    "employees":[ "Bill", "Steve", "David" ]
    }
  • 布尔
    { "sale":true }
  • Null
    { "middlename":null }

JSON 的值不可以是以下数据类型之一:

  • 函数

  • 日期

  • undefined

6. JSON.parse()

  • 实例-解析JSON:

    • JavaScript 函数 JSON.parse() 把文本转换为 JavaScript 对象

<p id="demo"></p>

<script>
var text = '{"employees":[' +
'{"firstName":"Bill","lastName":"Gates" },' +
'{"firstName":"Steve","lastName":"Jobs" },' +
'{"firstName":"Elon","lastName":"Musk" }]}';

obj = JSON.parse(text);
document.getElementById("demo").innerHTML =
obj.employees[1].firstName + " " + obj.employees[1].lastName;
</script>
  • 来自服务器的JSON:

    • 只要服务器的响应是用 JSON 格式编写的,你可以将字符串解析成 JavaScript 对象

var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function()  {
    if (this.readyState == 4 && this.status == 200) {
        myObj =  JSON.parse(this.responseText);
        document.getElementById("demo").innerHTML  = myObj.name;
    }
};
xmlhttp.open("GET", "json_demo.txt", true);
xmlhttp.send();
  • 作为 JSON 的数组

var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function()  {
    if (this.readyState == 4 && this.status == 200) {
        myArr =  JSON.parse(this.responseText);
        document.getElementById("demo").innerHTML  = myArr[0];
    }
};
xmlhttp.open("GET", "json_demo_array.txt", true);
xmlhttp.send();
  • 例外1:

    • 解析日期

    • JSON 中不允许日期对象。如果您需要包含日期,请写为字符串。之后您可以将其转换回日期对象:

var text =  '{ "name":"Bill Gates", "birth":"1955-10-28", "city":"Seattle"}';
var obj = JSON.parse(text);
obj.birth = new Date(obj.birth);
 
document.getElementById("demo").innerHTML = obj.name + ", " + obj.birth;
  • 将字符串转换为日期,使用 reviver 函数:

var text =  '{ "name":"Bill Gates", "birth":"1955-10-28", "city":"Seattle"}';
var obj = JSON.parse(text, function (key, value) {
    if  (key == "birth") {
        return new Date(value);
    } else {
         return value;
   }});
 
document.getElementById("demo").innerHTML = obj.name + ", " + obj.birth;
  • 例外2:

    • JSON 中不允许函数。

      如果您需要包含函数,请把它写作字符串。

      稍后您可以把它转换回函数:

    • var text =  '{ "name":"Bill Gates", "age":"function () {return 62;}", "city":"Seattle"}';
      var obj = JSON.parse(text);
      obj.age = eval("(" + obj.age + ")");
       
      document.getElementById("demo").innerHTML = obj.name + ", " +  obj.age();

7. JavaScript对象进行字符串化

  • 在向 web 服务器发送数据时,数据必须是字符串。

  • Stringify JavaScript对象

    • var obj = { name:"Bill Gates", age:62, city:"Seattle"};
      var myJSON =  JSON.stringify(obj);
      document.getElementById("demo").innerHTML = myJSON;
  • Stringify JavaScript 数组

  • var arr = [ "Bill Gates", "Steve Jobs", "Elon Musk" ];
    var myJSON =  JSON.stringify(arr);
    document.getElementById("demo").innerHTML = myJSON;
  • 例外1:

    • 在 JSON 中,不允许日期对象。JSON.stringify() 函数将把任何日期转换为字符串。

    • var obj =  { "name":"Bill Gates", "today":new Date(), "city":"Seattle"};
      var myJSON = JSON.stringify(obj);
      document.getElementById("demo").innerHTML = myJSON;
  • 例外2:

    • 在 JSON 中,不允许函数作为对象值。

      JSON.stringify() 函数将从 JavaScript 对象删除任何函数,包括键和值:

    • var obj =  { "name":"Bill Gates", "age":function () {return 62;}, "city":"Seattle"};
      var myJSON = JSON.stringify(obj);
      document.getElementById("demo").innerHTML = myJSON;
  • 如果您在运行 JSON.stringify() 函数前已将函数转换为字符串,这个环节可以省略。

    • var obj =  { "name":"Bill Gates", "age":function () {return 62;}, "city":"Seattle"};
      obj.age = obj.age.toString();
      var myJSON = JSON.stringify(obj);
      document.getElementById("demo").innerHTML = myJSON;
    • 需要使用 eval() 将它们转换回函数

8.JSON对象

  • 对象语法

  • { "name":"Bill Gates", "age":62, "car":null }
    • 键必须是字符串,值必须是有效的 JSON 数据类型(字符串、数字、对象、数组、布尔或 null)。

  • 访问对象值

    • myObj =  { "name":"Bill Gates", "age":62, "car":null };
      x = myObj.name;
    • myObj =  { "name":"Bill Gates", "age":62, "car":null };
      x = myObj["name"];
  • 遍历对象:for-in

    • myObj =  { "name":"Bill Gates", "age":62, "car":null };
      for (x in myObj) {
         document.getElementById("demo").innerHTML  += x;
      }
    • myObj =  { "name":"Bill Gates", "age":62, "car":null };
      for (x in myObj) {
         document.getElementById("demo").innerHTML  += myObj[x];
      }
  • 嵌套的JSON对象

    • myObj =  {
         "name":"Bill Gates",
         "age":62,
         "cars": {
      	  "car1":"Porsche",
      	  "car2":"BMW",
      	  "car3":"Volvo"
         }
      }
    • x = myObj.cars.car2;
      //或者:
      x = myObj.cars["car2"];
  • 删除对象属性

    • delete myObj.cars.car1;

9.JSON数组

  • JSON 中的数组几乎与 JavaScript 中的数组相同。

  • 在 JSON 中,数组值的类型必须属于字符串、数字、对象、数组、布尔或 null。

  • 在 JavaScript 中,数组值可以是以上所有类型,外加任何其他有效的 JavaScript 表达式,包括函数、日期和 undefined。

  • JSON对象中的数组

    • {
      "name":"Bill Gates",
      "age":62,
      "cars":[ "Porsche", "BMW", "Volvo" ]
      }
  • 访问数组值

    • x = myObj.cars[0];
  • 遍历数组

    • for (i in myObj.cars) {
           x  += myObj.cars[i];
      }
  • JSON对象中的嵌套数组

    • myObj =  {
         "name":"Bill Gates",
         "age":62,
         "cars": [
      	  { "name":"Porsche",  "models":[ "911", "Taycan" ] },
      	  { "name":"BMW", "models":[ "M5", "M3", "X5" ] },
      	  { "name":"Volvo", "models":[ "XC60", "V60" ] }
         ]
      }
    • for (i in myObj.cars) {
          x += "<h1>" + myObj.cars[i].name  + "</h1>";
          for (j in myObj.cars[i].models) {
               x += myObj.cars[i].models[j];
          }
      }

⑦JS/JQueryDom选择器

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值