事件 jQuery 选择器 筛选器 样式操作 CSS操作 文本操作

发布时间 2023-04-19 21:22:16作者: DRAMA-娜娜

事件

事件可以理解为:给HTML标签添加了一些额外的功能,并且能够触发JS的代码运行

1.事件就是达到某个触发条件,自动触发的动作
2.常用的事件
	1.onclick:当用户点击某个对象是调用的事件句柄
  2.onfoucus:元素获取焦点
  3.onblur:元素失去焦点
  4.onchange:域的内容被改变
  5.onload:一张页面或一幅画像完成加载
  6.onmouseout:鼠标从某元素移开
  7.onmouseover:鼠标移到某元素之上

常用事件

1.onclick        当用户点击某个对象时调用的事件句柄。
2.ondblclick     当用户双击某个对象时调用的事件句柄。
3.onfocus        元素获得焦点。// 练习:输入框
4.onblur         元素失去焦点。//应用场景:用于表单验证,用户离开某个输入框时,代表已经输入完了,我们可以对它进行验证.
5.onchange       域的内容被改变。//应用场景:通常用于表单元素,当元素内容被改变时触发.(select联动)
6.onkeydown      某个键盘按键被按下。//应用场景: 当用户在最后一个输入框按下回车按键时,表单提交.
7.onkeypress     某个键盘按键被按下并松开。
8.onkeyup        某个键盘按键被松开。
9.onload         一张页面或一幅图像完成加载。
10.onmousedown    鼠标按钮被按下。
11.onmousemove    鼠标被移动。
12.onmouseout     鼠标从某元素移开。
13.onmouseover    鼠标移到某元素之上。
14.onselect      在文本框中的文本被选中时发生。
15.onsubmit      确认按钮被点击,使用的对象是form。

绑定方式

方式一:

提前写好函数,标签内部指定

<body>
    <标签名     事件= "函数名()">
    <script>
    function 函数名(){
        函数体
    }
    </script>
</body>
举例
<body>
<button onclick="f1()">点击</button>
<script>
        function f1(){
            alert('可以看见吗?')
        }
</script>
</body>

方式二

先查找标签,然后在批量绑定(推荐)

<script>
    标签对象.事件名= function (){
        函数体代码
    }
</script>
举例
<body>
<button id = 'btn'>点击</button>
<script>
    var btn = document.getElementById('btn')
    btn.onclick =  function (){
        alert('可以看见吗?')
    }
</script>
</body>

事件中的关键字this

表示触发事件的当前元素。在方式一中,this指代document文档;在方式二中this指代当前被操作的标签对象

<body>
<button onclick="f1()">点击我</button>
<button id = 'd1'>点击我</button>
<script>
    function f1(){
        alert('方式一')
        console.log(this) // Window
    }

    var btn = document.getElementById('d1')
    btn.onclick = function (){
        alert('方式二')
        console.log(this) //<button id = 'd1'>点击我</button>
    }

</script>
</body>

需求:点击按钮换背景颜色

<body>
<button id = 'd1'>点击我</button>
<script>


    var btn = document.getElementById('d1')
    btn.onclick = function (){
        btn.style.backgroundColor = 'red'
        console.log(this) //<button id = 'd1'>点击我</button>
    }

</script>
</body>

事件与函数带参数使用

<body>
<button onclick="f1(1,2)">点击我</button>
<script>
    function f1(a,b){

        console.log(a,b) // Window
    }
</script>
</body>

window.onload

当我们给页面上的元素绑定事件的时候,必须等到文档加载完毕;window.onload等待文档加载完毕之后再执行一些代码

<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script>
        window.onload = function () {
        }
    </script>
</head>

举例

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script>
    window.onload =  function (){
        var btn = document.getElementById('d1')
        btn.onclick = function (){
            alert('看见了')
        }

    }
</script>
</head>
<body>
<button id = 'd1'>点击我</button>
</body>
</html>

案例

点击一下就换背景颜色(开关灯案例)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
  <style>
    .c1 {
        height: 300px;
        width: 300px;
      border: 10px solid greenyellow;
        border-radius: 50%;

    }
    .change_red{
      background-color: red;
    }
    .change_blue{
      background-color: blue;
    }
  </style>
</head>
<body>
<div class="c1 change_red change_blue"></div>
<button id = 'd1'> 换颜色</button>
<script>
    var btn  = document.getElementById('d1')
    var div = document.getElementsByTagName('div')[0]
    btn.onclick = function (){
        div.classList.toggle('change_blue')
    }
</script>
</body>
</html>

input事件

input框有两个事件:1. 获取焦点 2. 失去焦点

获取焦点-onfocus()

<body>

<p>用户名:<input type="text" id = 'inp1' value="请输入用户名"></p>
<script>
  var inp1 = document.getElementById('inp1')
  inp1.onfocus = function (){
    this.value = ''
  }
</script>

</body>

失去焦点-onblur()

<body>
<p>用户名:<input type="text" id = 'inp1' value="请输入用户名"></p>
<script>
  var inp1 = document.getElementById('inp1')
  inp1.onfocus = function (){
    this.value = ''
  }
  inp1.onblur= function (){

      this.value = 'ok'
  }
</script>
</body>

举例:省市联动(onchange事件)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<select name="" id="se1"></select>
<select name="" id="se2"></select>

<script>
  //1.给sel标签添加东西
      var data = {
        "河北省": ["廊坊", "邯郸"],
        "北京": ["朝阳区", "海淀区", "大兴", "丰台"],
        "山东": ["威海市", "烟台市"]
    };
  //1.1找到sel标签
  var se1 = document.getElementById('se1')
  //1.2 往se1标签添加option标签
  for (var i in data){
    var pro = document.createElement('option')
      pro.innerText = i
      pro.value = i
      se1.appendChild(pro)
  }

  se1.onchange = function (){
  //2.1找
  var se2 = document.getElementById('se2')
  //2.2添加option标签
  var current_pro = se1.value
  var current_city_list = data[current_pro]

   se2.innerText= ''
  for (var j = 0 ;j<current_city_list.length;j++){

      var city = document.createElement('option')
      city.innerText = current_city_list[j]
      city.value = current_city_list[j]
      se2.appendChild(city)
  }
  }

</script>
</body>
</html>

jQuery简单介绍

1.jQuery:他的内部封装了很多js代码,并且额外增加了很多的功能--他就是js的一个类库
			在python中,我们有模块这个概念,js中没有模块的概念,js是类库的概念,类库就相当于是我们的模块
2.jquery是对js 的一个高度封装,我们直接学习封装之后的代码

3.jquery介绍.
    1. jQuery是一个轻量级的、兼容多浏览器的JavaScript库。(使用jquery不用担心兼容性问题)
    2. jQuery使用户能够更方便地处理HTML Document、Events、实现动画效果、方便地进行Ajax交互,能够极大地简化JavaScript编程。它的宗旨就是:“Write less, do more.“
		3. 要想使用jquery,必须下载使用它,然后引入都我们的html文档中
		4. 下载的这个jquery文件大小只要即是KB,很小,几乎不影响加载速度
    5.jQuery的链式操作可以把多个操作写在一行代码里,更加简洁。
    
4.jQuery学习内容
		1. 选择器
    2. 筛选器
    3. 样式操作
    4. 文本操作
    5. 属性操作
    6. 文档处理
    7. 事件
    8. 动画效果
    9. 插件
    10. each、data、Ajax(放在Django中学---》重要)


5.jQuery版本 :1.x 2.x 3.x(学习最新版本)
6.jquery文件下载
    1.官网:https://jquery.com/
    2.第三方:https://jquery.cuishifeng.cn/index.html
    3.bootcdn:https:https://www.bootcdn.cn/
				1  .js  是没有压缩
        2  .min.js    是压缩的(下载)
    		3  网络CDN服务,只要计算机能够联网就可以直接导入(稳定、快速、免费的前端开源项目CDN加速服务:https://www.bootcdn.cn/)

7.使用jquery文件两种方式
    1.把文件下载下来,离线使用(另存为)
        在pythom中的 file and code templates 添加(不用每次都添加了)
    2.不下载,直接通过cdn链接使用

jQuery基本使用

jQuery基本语法

1.最开始
	jQuery('选择器').action()
2.后面
	$('选择器').action()

JS与jQuery语法对比

<body>
<h1 id = 'h1' class="c1" >hello</h1>
<h1 id = 'h2' class="c1">hello</h1>
</body>
<script>
    var h1 = document.getElementById('h1')
    h1.style.color = 'red'
    console.log(h1) //<h1 id = 'h1' className="c1" style="color: red;">hello</h1>

    var h2 = $('#h2').css('color','blue')
    console.log(h2) //S.fn.init[h1#h2.c1]
</script>

基本选择器

id选择器

$("#id")

标签选择器

$("tagName")

class选择器

$(".className")

所有元素选择器

$("*")

配合使用

$("div.c1")  // 找到有c1 class类的div标签
<body>
<div id ='d1' > div</div>
<p class="c1 c2">p c1c2</p>
<p class="c1 c3">p c1c2</p>
<h>h</h>
<script>
  //1.找到id为d1的标签,字体设为绿色
  $('#d1').css('color','red')

  //2.将类c2的字体设为绿色
  $('.c2').css('color','green')

  //3.将h标签字体设置为蓝色
  $('h').css('color','blue')

  //4.将p标签的c2类,字体设黄色
  $('p.c2').css('color','yellow')
</script>
</body>

组合选择器

$("#id, .className, tagName") //逗号分开代表的是并列关系
<body>
<div class="c1" id="d1"> div c1 d1</div>
<span class="c1 c2"> span c1 c2</span>
<p class="c1 ">p c1</p>
<h>h</h>

<script>
  //将id为d1的标签和类为c2的标签以及h标签,字体设为红色
  $('#d1,.c2,h').css('color','red')
</script>
</body>

层级选择器

$("x y")  // x的所有后代y(子子孙孙)后代
$("x > y")  // x的所有儿子y(儿子) 儿子
$("x + y")  // 找到所有紧挨在x后面的y 毗邻
$("x ~ y")  // x之后所有的兄弟y 兄弟
<body>
<div id = 'd1'>div
  <div>div div
    <span>  |div div span</span>
  </div>
    <h id = 'd2'>div h</h>
    <p>ppppppppp</p>
  <span>|div span</span>
  <p>div p</p>

</div>
<h id = 'd3'>h</h>
<div>divdiv</div>
<script>
    //1.将id为1的标签下的span标签字体设置为红色
    $('#d1 span').css('color','red')

    //2.将id为1的标签下的第一层级下的span标签字体设置为蓝色
    $('#d1>span').css('color','blue')

    //3.将id为d2下紧挨着的p标签,字体设置黄色
    $('#d2 + p').css('color','yellow')

    //4.将id为d3t的p标签,字体设置紫色
    $('#d3~div').css('color','purple')

</script>
</body>

属性选择器

[attribute]
[attribute=value]// 属性等于
[attribute!=value]// 属性不等于
</head>
<body>
<div class="c1" username="kevin">11</div>
<input type="text" disabled="disabled">
<input type="password">
<input type="checkbox">

<script>
  //1.获取属性含有username的标签,字体设为红色
    $('[username]').css('color','red')

  //2.获取属性disabled="disabled的标签
    var dis1 = $('[disabled="disabled"]')
  console.log(dis1)  //S.fn.init [input, prevObject: S.fn.init(1)]

  //3.获取input标签中,type="checkbox"的标签
  var inp  = $('input[type="checkbox"]')
  console.log(inp) //S.fn.init [input, prevObject: S.fn.init(1)]

</script>
</body>

jQuery选择器查找标签之后的结果与JS有何区别

jQuery选择器与JS查找标签之后的结果集都是数组,但是功能有区别

$('p')  // S.fn.init(2) [p, p, prevObject: S.fn.init(1)]
document.getElementsByTagName('p')  //HTMLCollection(2) [p, p]

1.如果使用索引取值,那么都标签对象,标签对象是无法调用jQuery提供的方法的

$('p')[0]  //<p style="color: red;">今天周五</p>
document.getElementsByTagName('p')[0]  //<p style="color:red;">今天周五</p>

$('p')[0].css('color','red')//VM1235:1 Uncaught TypeError: $(...)[0].css is not a function
$('p')[0].style.color = 'red'  //'red'
$('p').first().style.color = 'green'   //VM1626:1 Uncaught TypeError: Cannot set properties of undefined (setting 'color')

2.标签对象如果想转换成jQuery对象需要使用:$() ;转换成jQuery对象的目的是为了使用jQuery提供的更多方法

$(document.getElementsByTagName('p')[0]) //S.fn.init [p]0: plength: 1[[Prototype]]: Object(0)
$(document.getElementsByTagName('p'))  //S.fn.init(2) [p, p]

$($('p')[0]).css('color','orange')  //jQuery.fn.init [p]

基本筛选器

筛选器 含义 例子
:first 第一个 $("li:first"))
:last 最后一个 $("li:last")
:eq(index) 索引等于index的那个元素 $("li:eq(4)")
:even 匹配所有索引值为偶数的元素,从 0 开始计数 $("li:even")
:odd 匹配所有索引值为奇数的元素,从 0 开始计数 $("li:odd")
:gt(index) 匹配所有大于给定索引值的元素 $("li:gt(4)")
:lt(index) 匹配所有小于给定索引值的元素 $("li:lt(4)")
:not(元素选择器) 移除所有满足not条件的标签 $("li:not(.c1)"
:has(元素选择器) 选取所有包含一个或多个标签在其内的标签(指的是从后代元素找) $("div:has(.c1)")

例子

$("div:has(h1)")// 找到所有后代中有h1标签的div标签
$("li:not(.c1)")// 找到所有不包含c1样式类的li标签
$("li:not(:has(a))")// 找到所有后代中不含a标签的li标签
<body>
<ul>
  <li>1111111</li>
  <li>2222222</li>
  <li class="c1">3333333</li>
  <li id = 'd1'>4444444</li>
  <li>5555555</li>
</ul>
<li>66666666</li>
<script>
  //1.li的第一个标签字体变为红色
  $('li:first').css('color','red')

  //2.li的最后一个标签字体变为黄色
  $('li:last').css('color','yellow')

  //3.li标签第6个 字体设为蓝的
  $('li:eq(5)').css('color','blue')

  //4.li标签索引为偶数的标签字体紫色
  $("li:even").css('color', 'brown')

  //5.li标签索引为偶数的标签字体紫色
  $("li:odd").css('color', 'pink')

  //6.li标签索引大于3字体橙色
  $('li:gt(3)').css('color','orange')

  //7.li标签索引小于3字体橙色
  $('li:lt(3)').css('color','pink')

  //8.li标签中,除了id为d1的其他字体为红色
  $('li:not(#d1)').css('color','red')

  //
  $('li:has(.c1)').css('color','blue')

</script>
</body>

表单筛选器

表单筛选器可以看成是属性选择器优化而来 eg:$('input[type="text"]') $(":Text")

表单筛选器 举例 等价于
:text $(":Text") $('input[type = "text"]')
:password $(":password") $('input[type = "password"]')
:file $(":file") $('input[type = "file"]')
:radio $(":radio") $('input[type = "radio"]')
:checkbox $(":checkbox") $('input[type = "checkbox"]')
:submit $(":submit") $('input[type = "submit"]')
:reset $(":reset") $('input[type = "reset"]')
:button $(":button") $('input[type = "button"]')

表单对象属性

:checked

当下拉列表设置默认值的时候,通过$(":checked")筛选的时候,也会被查找出来

$(":checked")  //[input.c, input.c, input.c, option, prevObject: jQuery.fn.init(1)]

:selected

$(":selected")只能查找下拉列表被设置默认

$(":selected")  // [option, prevObject: jQuery.fn.init(1)]

:disabled

<p><input type="text" class="c" disabled value="不能输入吧">1</p>

$(":disabled")  //S.fn.init [input.c, prevObject: S.fn.init(1)]

<body>
<input type="text" name="" id="">
<input type="radio" value="1" name="gender"> 男
<input type="radio" value="2" checked name="gender"> 女
<select id="s1">
    <option value="beijing">北京市</option>
    <option value="shanghai">上海市</option>
    <option selected value="guangzhou">广州市</option>
    <option value="shenzhen">深圳市</option>
</select>
<script>
  //1.type="text"属性,设置背景颜色
  $(':text').css('backgroundColor','red')

  //2.查找checked= 'checked'标签
  var che = $(':checked')
  console.log(che)  //S.fn.init(2) [input, option, prevObject: S.fn.init(1)]

  //3.查找selected= 'selected'标签
  var sel = $(':selected')
  console.log((sel))  //S.fn.init [option, prevObject: S.fn.init(1)]

  //4.查找disabled = ‘disabled’标签
  var dis = $(':disabled')
  console.log(dis)
</script>
</body>

筛选器方法

jquery调用方法之后返回的结果还是jquery对象,所以你就可以继续点jquery给你提供的方法,这叫链式操作

下一个元素

$("#id").next()
$("#id").nextAll()
$("#id").nextUntil("#i2")
<body>
<div id="d1">div</div>
<p class="c1">pppppp</p>
<p class="c1">pppppp</p>
<p class="c1">pppppp</p>
<p class="c1">pppppp</p>
<span class="s1" id="i2">span</span>
<p class="c1">pppppp</p>
<script>
  //将id = d1 下的一个标签设置背景边框
  $('#d1').next().css('height','300px').css('backgroundColor','red').css('border','10px solid blue')

  //将id = d1 下的所有标签字体设置为蓝色
  $('#d1').nextAll().css('color','blue')

  //将id = d1 下到id = i2   字体设置为绿色
  $('#d1').nextUntil('#i2').css('color','green')
</script>
</body>

上一个元素

$("#id").prev()
$("#id").prevAll()
$("#id").prevUntil("#i2")

父亲元素

$("#id").parent()
$("#id").parents()  // 查找当前元素的所有的父辈元素
$("#id").parentsUntil() // 查找当前元素的所有的父辈元素,直到遇到匹配的那个元素为止。

儿子和兄弟元素

$("#id").children();// 儿子们
$("#id").siblings();// 兄弟们

查找

搜索所有与指定表达式匹配的元素。这个函数是找出正在处理的元素的后代元素的好方法。

$("div").find("p")----------------->等价于$("div p")
$("div").find("p")----------------->等价于$("div p")
$(".c1").find("a")----------------->等价于$(".c1 a")

筛选

筛选出与指定表达式匹配的元素集合。这个方法用于缩小匹配的范围。用逗号分隔多个表达式。

$("div").filter(".c1")  // 从结果集中过滤出有c1样式类的 --- $("div.c1")

补充

1 .first() :获取匹配的第一个元素
  	$('div span:first')-------------->$('div span').first()
2 .last() :获取匹配的最后一个元素
      $('div span:last')----------------->$('div span').last()
3 .not() :从匹配元素的集合中删除与指定表达式匹配的元素
      $('div span:not("#d3")') --------------->$('div span').not('#d3')
4 .has() :保留包含特定后代的元素,去掉那些不含有指定后代的元素。
5 .eq() : 索引值等于指定值的元素

样式操作

1.addClass();  添加指定的CSS类名。
		ps:classList.add()
2.removeClass();  移除指定的CSS类名。
		ps:classList.remove()
3.hasClass();  判断样式存不存在
		ps:classList.contains()
4.toggleClass();   切换CSS类名,如果有就移除,如果没有就添加。
		ps:classList.toggle()
<body>
<div class="c1" id="d1">div</div>
<script>
  //1.给ID=d1的添加属性c2,c3,c4
  var div =$('#d1').addClass('c2').addClass('c3').addClass('c4')
    console.log(div[0])

  //2.给ID=d1的s删除属性c2
  var div1 = $('#d1').removeClass('c2')
  console.log(div1[0])

  //3.判断ID=d1的属性c2在不在
  console.log($('#d1').hasClass('c2')) //false

  //4.c2不再添加,在就删除
  var div2 = $('#d1').toggleClass('c2')
  console.log(div2[0])
    var div3 = $('#d1').toggleClass('c2')
  console.log(div3[0])
</script>
</body>

css操作

可链式操作

css("color","red")//DOM操作:tag.style.color="red"
$("p").css("color", "red").css('','').css('',''); 

文本操作

HTML代码:

1.html(): 取得第一个匹配元素的html内容--识别标签
	  eg:
		console.log($('.c1').html())  //<h1>加油</h1>

2.html(val):设置所有匹配元素的html内容 --不识别标签
	.innerHTML = 'val'
   eg:
  	$('.c1').html('看见')

文本值

1.text()/:取得所有匹配元素的内容
	  eg:
		console.log($('.c1').text())  //加油
2.text(val)// 设置所有匹配元素的内容
	.innerText = 'val'
		eg:
		 $('.c1').text('遇见')
<body>
<div class="c1"><h1>加油</h1></div>
<input type="text" id="inp1" value="hahahaha">
<script>
  console.log($('.c1').html())  //<h1>加油</h1>
  console.log($('.c1').text())  //加油

   $('.c1').html('看见')
    $('.c1').text('遇见')
</script>

</body>

1.val():取得第一个匹配元素的当前值
				eg:
			   console.log($('#inp1').val()) //hahahaha
2.val(val):设置所有匹配元素的值
				eg:
				var inp = $('#inp1').val('helloworld');
        console.log($('#inp1').val());  //helloworld
3.val([val1, val2]):设置多选的checkbox、多选select的值

文本登陆案例

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="jquery.min.js"></script>
      <style>
        .error {
            color: red;
        }
    </style>
</head>
<body>
<form action="">
<div>
    <label for="user_name">
  用户名:<input type="text" id = 'user_name' name = 'name'>
</label>
  <span class="error"></span>
</div>
<div>
  <label for="pass_word">
  密码:<input type="password" id = "pass_word" name = 'password'>
</label>
  <span class="error"></span>
</div>
<div>
    <input type="button" value="提交" id = 'btn'>
</div>
</form>
<script>
  var btn = $('#btn');
  btn.click(function () {
    //1.获取用户密码、值
    var username = $('#user_name').val()
    var password = $('#pass_word').val()

    //2.判断值是否为空
    if (!username){
      $('.error:first').text('用户名不能为空')
    }
    if (!password){
      $('.error:last').text('密码不能为空')
    }
  })

</script>
</body>
</html>

页面定时器案例

有一个input框 、两个按钮(一个开始、 一个结束)
1.点击开始按钮 input内展示当前时间并按秒数刷新
2.点击结束按钮 input内展示停止
ps:写完之后测试有无bug,连续多次点击开始按钮,再试试能不能结束(思考如何解决)


搜索框案例

input内有默认的文本值 用户一旦选择该input想做内容修改就提前把内容清空