js

JS

一、数据类型

1.1 分类

​ 字符串、数值、布尔值、数组、对象

1.2 字符串类型

  • 字符串用单引号或者双引号包裹,转义用:\;

    var Name = "lol";   // 使用双引号
    var Name = 'lol';   // 使用单引号
    var Name = " lol\' " //转义 '多行字符串编写
    
  • 多行字符串编写

    var str = 
        `hello
    world
    你好
    `
    
  • 模板字符串

    let name = "anhaodong"
    let msg = `你好,${name}`
    
  • 字符串长度

    var str = 'student'
    console.log(str.length)
    
  • 字符串不可变

  • 大小写转换(方法)

    var str = 'student'
    str.toupperCase()//转大写
    str.tolowerCase()//转小写
    

1.3 数组类型

  • 可以包含任意的数据类型

    var arr = [1,2,3,4,'stodent']
    
  • 长度

    arr.length
    //给arr.length赋值,数组大小就会发生变化,如果赋值过小,元素就会丢失
    
  • indexOf

    //通过元素获得下标索引
    var arr = [1,2,3,4]
    arr.indexOf(2)
    //2的下标为:1
    
  • slice()

    //截取数组的一部分,返回一个新的数组
    //左闭右开,取千不取后
    var arr = [1,2,3,4,5,6]
    slice(2)//结果:[3,4,5,6]
    slice(1,3)//结果:[2,3]
    
  • push()、pop()

    //操作尾部
    var arr = [1,2,3,4,"a"]
    push('b','c')//在数组末尾添加
    pop()//弹出最后一个元素
    
  • unshift(),shift()

    //操作头部
    var arr = [1,2,3,4,"a"]
    unshift('b','c')//在数组头部添加
    shift()//弹出头部一个元素
    
  • 排序sort()

    var arr = ["B","C","A"]
    arr.sort()
    
  • 元素反转reverse()

    var arr = ["A","B","C"]
    arr.reverse
    //["C","B","A"]
    
  • 拼接concat()

    var arr = ["B","C","A"]
    arr.concat([1,2,3])
    //["B","C","A",1,2,3]
    
  • 连接符join

    //打印拼接字符串,使用特定的字符连接
    var arr = ["B","C","A"]
    arr.join('-')
    //"B-C-A"
    
  • 多维数组

    var arr = [[1,2],[3,4],["5","6"]]
    

1.4 对象类型

  • 若干个键值对,js中所有的键都是字符串,值是任意的对象

    var person = {
        name: "anhaodong",
        age: 3,
        email: "123456@qq.com"
    }
    
  • 赋值

    person.name = "anhaodong"
    //取值
    person.name  //结果:"anhaodong"
    
    person.haha //取一个不存在的对象属性不会报错,显示undefind
    
  • 动态删减属性

    //通过delete删除对象的属性
    delete person.name
    
  • 动态添加属性

    //直接给新的属性添加值
    person.haha = "haha"
    
  • 判断属性值是否存在

    'age' in person 
    true
    
    //继承
    'toString' in person
    true
    
  • 判断属性是否是这个对象自身拥有的

    person.hasOwnProperty('toString')
    false
    person.hasOwnProperty('age')
    true
    

二、函数

2.1 定义函数

function myFunction1(p1, p2) {
    return p1 * p2;              // 该函数返回 p1 和 p2 的乘积
}

var x = function myFunction2(p1,p2){return p1 * p2;}

//箭头函数
// ES5
var x = function(x, y) {
  return x * y;
}
// ES6
const x = (x, y) => x * y;

【注】

  • 执行到return代表篇函数结束,返回结果;如果没有return,函数执行完也会返回结果。

2.2函数的参数

参数问题:可以传任何参数,也可以不传参数。

  • arguments 对象
/**
	arguments是一个数组,存储向函数传的所有参数
*/
var x = myFunction(1,2,3,4)

function myFunction(){
    var i;
    for(i=0;i<arguments.length;i++){
        console.log(arguments[i]);
    }
}

2.3 函数的调用

(1)函数中的代码将在其他代码调用该函数时执行:

  • 当事件发生时(当用户点击按钮时)
  • 当 JavaScript 代码调用时
  • 自动的(自调用)
function myFunction(a, b) {
    return a * b;
}
myFunction(10, 2);           // 将返回 20

(2)作为方法

var myObject = {
    firstName:"Bill",
    lastName: "Gates",
    fullName: function () {
        return this.firstName + " " + this.lastName;
    }
}
myObject.fullName();         // 将返回 "Bill Gates"

2.4 call()和apply()

相似:编写用于不同对象的方法。

区别:call() 方法分别接受参数;

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

  • 预定义的js方法,能够调用不同对象的方法。
var person = {
    fullName: function() {
        return this.firstName + " " + this.lastName;
    }
}
var person1 = {
    firstName:"Bill",
    lastName: "Gates",
}
var person2 = {
    firstName:"Steve",
    lastName: "Jobs",
}
person.fullName.call(person1);  // 将返回 "Bill Gates"
  • 带参数:
//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");


//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"]);

2.5 函数的返回

var x = myFunction(7, 8);        // 调用函数,返回值被赋值给 x

function myFunction(a, b) {
    return a * b;                // 函数返回 a 和 b 的乘积
}

// x: 56

三、遍历

3.1 for

var arr = [1, 2, 3]
for(var i = 0; i < arr.length; i++) { // 这里的i是代表数组的下标
    console.log(i); // 0, 1, 2
};

3.2 for...of...

var arr = [1, 2, 3]
for(var item of arr) { // item代表数组里面的元素
    console.log(item); // 1, 2, 3
}; 

3.3 forEach()

var arr = [1, 2, 3];
arr.forEach((item, index, arr) => { // item为arr的元素,index为下标,arr原数组
    console.log(item); // 1, 2, 3
    console.log(index); // 0, 1, 2
    console.log(arr); // [1, 2, 3]
});

3.4 for...in...

var arr = [1, 2, 3]
for(var item in arr) { // item遍历数组时为数组的下标,遍历对象时为对象的key值
    console.log(item); // 0, 1, 2
};

3.5 map()

var arr = [1, 2, 3];
arr.map(item => { // item为数组的元素
    console.log(item); // 1, 2, 3
    return item * 2; // 返回一个处理过的新数组[2, 4, 6]
})

四、事件

4.1 概念

(1)事件:是发生在 HTML 元素上的“事情”,常见的事件:鼠标事件,键盘事件,窗口事件,表单事件,也有可能是页面加载资源过程中的事件。

2)例:鼠标点击事件

<button onclick='document.getElementById("demo").innerHTML=Date()'>现在的时间是?</button>

4.2事件属性

  • 向 HTML 元素分配事件,使用事件属性。
<button onclick="displayDate()">时间是?</button>

<script>
function displayDate() {
  document.getElementById("demo").innerHTML = Date();
}
</script>

<p id="demo"></p>
  • 使用 JavaScript 向 HTML 元素分配事件。
<button id="myBtn">试一试</button>

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

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

function displayDate() {
  document.getElementById("demo").innerHTML = Date();
}
</script>

4.3 onmouseover 和 onmouseout 事件

  • onmouseover 和 onmouseout 事件可用于当用户将鼠标移至 HTML 元素上或移出时触发某个函数:
<div onmouseover="mOver(this)" onmouseout="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>

4.4 onmousedown, onmouseup 以及 onclick 事件

  • onmousedown, onmouseup 以及 onclick 事件构成了完整的鼠标点击事件。

    首先当鼠标按钮被点击时,onmousedown 事件被触发;然后当鼠标按钮被释放时,onmouseup 事件被触发;最后,当鼠标点击完成后,onclick 事件被触发。

<div onmousedown="mDown(this)" onmouseup="mUp(this)"
style="background-color:#D94A38;width:90px;height:20px;padding:40px;">
点击鼠标</div>

<script>
function mDown(obj) {
  obj.style.backgroundColor = "#1ec5e5";
  obj.innerHTML = "松开鼠标";
}

function mUp(obj) {
  obj.style.backgroundColor="#D94A38";
  obj.innerHTML="谢谢您";
}
</script>

五、jQuery

5.1 格式

$(selector).action()

//selector:选择器
//action():事件

5.2 常见选择器

1)基本选择器:基本选择器是jQuery中最常用也是最简单的选择器,它通过元素的id、class和标签名等来查找DOM元素。

  • ID选择器
$("#test")//选取id为test的元素,返回单个元素
  • 类选择器
$(".test")//选取所有class为test的元素,返回元素集合
  • 元素选择器
$("p")//选取所有<p>标签的元素,返回元素集合
$("*")//选取所有的元素,返回元素集合
  • selector1,selector2,...,selectorN
$("p,span,p.myClass")//选取所有<p>,<span>和class为myClass的<p>便签元素集合

(2)层次选择器:根据层次关系获取特定元素。

  • 后代选择器
$("p span")//选取<p>元素里所有的<span>元素
  • 子代选择器
$("p>span")//选取直属于<p>元素的所有<span>元素
  • 同辈选择器
$("prev~siblings")//选取prev元素后的所有siblings元素,返回元素集合
$("#two~p")//选取id为two的元素后所有同辈元素集合

(3)基本过滤选择器

  • first
$("p:first")//选取所有<p>元素中第一个<p>元素
  • last
$("p:last")//选取所有<p>元素中的最后一个<p>元素
  • not
$("input:not(.myClass)")//class不是myClass的<input>元素

(4)内容过滤选择器

  • contains
$("p:contains('我')")//选取含有文本“我”的元素
  • empty
$("p:empty")//选取不包含子元素或者文本元素空的<p>元素
  • has
$("p:has(p)") 选取含有<p>元素的<p>元素
  • parent
$("p:parent") 选取含有子元素或者文本元素的<p>元素

(5)属性过滤选择器

  • [attribute]
$("p[id]") //选取拥有id属性的<p>元素
  • [attribute = value]
$("input[name=text]")// 选取拥有name属性等于text的<input>元素
  • [attribute != value]
$("input[name!=text]")// 选取拥有name属性不等于text的<input>元素

(6)表单选择器

  • :text
$(":test")//选取所有的单行文本框
  • :password
$(":password")//选择所有的密码框
  • :butten
$(":butten")//选择所有的按钮
  • checkbox
$(":checkbox")//选取所有的多选框

5.3 遍历

(1)遍历-祖先

  • parent()
/**
parent() 方法返回被选元素的直接父元素。
该方法只会向上一级对 DOM 树进行遍历。
*/
$(document).ready(function(){
  $("span").parent();
});
  • parents()
/**
parents() 方法返回被选元素的所有祖先元素,它一路向上直到文档的根元素 (<html>)。
*/
$(document).ready(function(){
  $("span").parents();
});


//返回所有 <span> 元素的所有祖先,并且它是 <ul> 元素:
$(document).ready(function(){
  $("span").parents("ul");
});
  • paarentsUntil()
/**
parentsUntil() 方法返回介于两个给定元素之间的所有祖先元素。
*/
$(document).ready(function(){
  $("span").parentsUntil("div");
});

(2)遍历-后代

  • children()
/**
children() 方法返回被选元素的所有直接子元素。
该方法只会向下一级对 DOM 树进行遍历。
*/
$(document).ready(function(){
  $("div").children();
});

//返回类名为 "1" 的所有 <p> 元素,并且它们是 <div> 的直接子元素
$(document).ready(function(){
  $("div").children("p.1");
});
  • find()
/**
find() 方法返回被选元素的后代元素,一路向下直到最后一个后代。
*/

//返回属于 <div> 后代的所有 <span> 元素
$(document).ready(function(){
  $("div").find("span");
});

//返回 <div> 的所有后代
$(document).ready(function(){
  $("div").find("*");
});

(3)遍历-同胞

  • siblings()
/**
返回被选元素的所有同胞元素
*/
$(document).ready(function(){
  $("h2").siblings();
});

//返回属于 <h2> 的同胞元素的所有 <p> 元素
$(document).ready(function(){
  $("h2").siblings("p");
});
  • next()
/**
next() 方法返回被选元素的下一个同胞元素。
该方法只返回一个元素。
*/
$(document).ready(function(){
  $("h2").next();
});
  • nextAll()
/**
返回被选元素的所有跟随的同胞元素。
*/
$(document).ready(function(){
  $("h2").nextAll();
});
  • nextUntil()
/**
返回介于两个给定参数之间的所有跟随的同胞元素。
*/
$(document).ready(function(){
  $("h2").nextUntil("h6");
});

(4)遍历-过滤

  • first()
/**
first() 方法返回被选元素的首个元素。
*/

//选取首个 <div> 元素内部的第一个 <p> 元素
$(document).ready(function(){
  $("div p").first();
});
  • eq()
/**
返回被选元素中带有指定索引号的元素
索引号从 0 开始,因此首个元素的索引号是 0 而不是 1
*/

//选取第二个 <p> 元素(索引号 1)
$(document).ready(function(){
  $("p").eq(1);
});
  • filter()
/**
规定一个标准,不匹配这个标准的元素会被从集合中删除,匹配的元素会被返回
*/

//返回带有类名 "intro" 的所有 <p> 元素
$(document).ready(function(){
  $("p").filter(".intro");
});
  • note()
/**
not() 方法返回不匹配标准的所有元素。
not() 方法与 filter() 相反。
*/

//返回不带有类名 "intro" 的所有 <p> 元素
$(document).ready(function(){
  $("p").not(".intro");
});

5.4 操作html

(1)获取

  • text()、html()、val、attr()
/**
通过 jQuery text() 和 html() 方法来获得内容
*/
$("#btn1").click(function(){
  alert("Text: " + $("#test").text());
});
$("#btn2").click(function(){
  alert("HTML: " + $("#test").html());
});

/**
通过 jQuery val() 方法获得输入字段的值
*/
$("#btn1").click(function(){
  alert("Value: " + $("#test").val());
});

/**
获取属性值
*/
//获得链接中 href 属性的值
$("button").click(function(){
  alert($("#w3s").attr("href"));
});

(2)jQuery添加

  • 添加新内容的四个 jQuery 方法:
/**
append() - 在被选元素的结尾插入内容

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

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

before() - 在被选元素之前插入内容
*/
 $("#btn1").click(function(){
    $("p").append(" <b>Appended text</b>.");
  });

  $("#btn2").click(function(){
    $("ol").append("<li>Appended item</li>");
  });
    
  $("#btn1").click(function(){
    $("p").prepend("<b>Prepended text</b>. ");
  });
  $("#btn2").click(function(){
    $("ol").prepend("<li>Prepended item</li>");
  });

  • jQuery after() 和 before() 方法
/**
jQuery after() 方法在被选元素之后插入内容
jQuery before() 方法在被选元素之前插入内容
*/
$(document).ready(function(){
    
  $("#btn1").click(function(){
    $("p").before("<b>Before</b>");
  });

  $("#btn2").click(function(){
    $("p").after("<i>After</i>");
  });
});

(3)jQuery删除

  • jQuery remove() 方法
/**
jQuery remove() 方法删除被选元素及其子元素
*/
$("#div1").remove();
//删除 class="italic" 的所有 <p> 元素
$("p").remove(".italic");
  • jQuery empty() 方法
//jQuery empty() 方法删除被选元素的子元素
$("#div1").empty();

(4)jQuery操作CSS

  • jQuery addClass() 方法
//向不同的元素添加 class 属性。在添加类时,您也可以选取多个元素
$("button").click(function(){
  $("h1,h2,p").addClass("blue");
  $("div").addClass("important");
});
  • 在 addClass() 方法中规定多个类:
$("button").click(function(){
  $("#div1").addClass("important blue");
});
  • jQuery removeClass() 方法
//不同的元素中删除指定的 class 属性
$("button").click(function(){
  $("h1,h2,p").removeClass("blue");
});
  • jQuery toggleClass() 方法
//对被选元素进行添加/删除类的切换操作
$("button").click(function(){
  $("h1,h2,p").toggleClass("blue");
});
  • 设置 CSS 属性
$("p").css("background-color","yellow");
  • 设置多个 CSS 属性:
$("p").css({"background-color":"yellow","font-size":"200%"});

(5)jQuery操作尺寸

  • jQuery width() 和 height() 方法
/**
width() 方法设置或返回元素的宽度(不包括内边距、边框或外边距)
height() 方法设置或返回元素的高度(不包括内边距、边框或外边距)
*/
$("button").click(function(){
  var txt="";
  txt+="Width: " + $("#div1").width() + "</br>";
  txt+="Height: " + $("#div1").height();
  $("#div1").html(txt);
});
  • jQuery innerWidth() 和 innerHeight() 方法
/**
width() 方法设置或返回元素的宽度(不包括内边距、边框或外边距)
height() 方法设置或返回元素的高度(不包括内边距、边框或外边距)
*/
$("button").click(function(){
  var txt="";
  txt+="Inner width: " + $("#div1").innerWidth() + "</br>";
  txt+="Inner height: " + $("#div1").innerHeight();
  $("#div1").html(txt);
});
  • jQuery outerWidth() 和 outerHeight() 方法
/**
outerWidth() 方法返回元素的宽度(包括内边距和边框)
outerHeight() 方法返回元素的高度(包括内边距和边框)
*/
$("button").click(function(){
  var txt="";
  txt+="Outer width: " + $("#div1").outerWidth() + "</br>";
  txt+="Outer height: " + $("#div1").outerHeight();
  $("#div1").html(txt);
});
/**
outerWidth(true) 方法返回元素的宽度(包括内边距、边框和外边距)
outerHeight(true) 方法返回元素的高度(包括内边距、边框和外边距)
*/
$("button").click(function(){
  var txt="";
  txt+="Outer width (+margin): " + $("#div1").outerWidth(true) + "</br>";
  txt+="Outer height (+margin): " + $("#div1").outerHeight(true);
  $("#div1").html(txt);
});
  • 设置指定的
    元素的宽度和高度
$("button").click(function(){
  $("#div1").width(500).height(500);
});
posted @ 2020-08-27 14:18  Foreverless  阅读(93)  评论(0)    收藏  举报