jQuery基础学习笔记

jQuery基础学习

个人说明:本文所涉及的到各种jQuery中的函数,方法,api等都不完整,只是一些常用的方法而已,详情还得阅读官方文档

中文版:https://www.jquery123.com/

jQuery的简单介绍

jQuery:是一个快速,小,功能丰富的]avaScript库。它使诸如HTML文档遍历和操作,事件处理、动画和Ajax更简单和易于使用的API,跨越多种浏览器。结合的通 用性和可扩展性,jQuery已经改变了数百万人的方式编写JavaScript。

jQuery作为JavaScript封装的库,目的就是为了简化开发者使用

优势:强大的选择器,像css那样访问和操作dom,修改css控制页面外观,简化js代码操作,事件处理更加容易,各种动画效果使用方法,让ajax技术更加完美,基于jQuery大量插件,自行扩展功能插件,自行扩展功能插件,出色的浏览器兼容,链式操作方式,隐式迭代,完善的文档,开源等等优势

jQuery下载

jquery官网

https://jquery.com/download/

打开官网,找到以下字样

To locally download these files, right-click the link and select “Save as…” from the menu.

Download the compressed, production version:

Download jQuery 3.7.1

其中以下两个版本的区别

Download the uncompressed development version of jQuery 3.7.1 : 推荐在开发环境下使用,文件大

Download jQuery 3.7.1 : 推荐在项目上线使用,文件小

jQuery没有直接的下载方式,需要自己查看源码,然后自己复制源码到本地

例如,先下载一个开发环境下使用的jquery,点击 Download the uncompressed development version of jQuery 3.7.1 ,就会跳转页面显示源码,然后鼠标右键另存为到本地,即可完成下载

想要下载项目上线使用的版本,那就点击 Download jQuery 3.7.1 ,就会跳转页面显示源码,然后鼠标右键另存为到本地,即可完成下载

jQuery初使用

引入jquery包

<!--引入jquery包-->
<script src="jquery-3.7.1.js"></script>

使用jquery操控dom对象

 $('#元素id')[0];
 $('.元素class')[0];

jQuery测试案例

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<div id="app">hello world</div>
<!--引入jquery包-->
<script src="jquery-3.7.1.js"></script>
<script>
    // 当引入jquery包,就查看该对象了
    console.log(jQuery);

    // js对象转换成jquery对象
    var oDiv = document.getElementById('app');
    jQuery(oDiv);

    // jquery对象转换为js对象
    jQuery('#app')[0];

    // (推荐)更简便:用jquery太过麻烦,那就可以直接使用$
    $(oDiv); // js对象转jquery对象
    $('#app')[0]; // jquery对象转js对象
    $('#app').get(0); // jquery对象转js对象 等价于   $('#app')[0];
    
</script>
</body>
</html>

入口函数

js中的入口函数是window.onload = function(){};

jQuery中的入口函数是$(function(){});

区别:js中的入口函数重复使用会有覆盖现象,jquery的入口函数重复使用,不会有覆盖现象,会依次执行

onload和ready的区别

区别window.onload$(document).ready()
执行时机必须等待网页全部加载完毕(包括图片等),然后再执行包裹代码只需要等待网页中的DOM结构加载完毕,就能执行包裹的代码
执行次数只能执行一次,如果第二次,那么第一次的执行会被覆盖可以执行多次,第N次都不会覆盖上一次
简写方案$(function(){});

案例

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>入口函数</title>
    <script src="jquery-3.7.1.js"></script>
</head>
<body>
<div class="box">box</div>

<script type="text/javascript">
    //js的入口函数
    window.onload = function(){alert(1)}
    // js的重复入口函数会被覆盖
    window.onload = function(){alert(2)}

    // jquery的重复 入口函数 不会被覆盖,会依次执行
    // jquery的入口函数
    $(document).ready(function(){
        alert(3);
    })


    //jquery的入口函数 简写
    $(function(){
        alert(4);
    })

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

多个库$冲突的问题

场景复现

index.js文件

var $ = 4;

html文件

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>入口函数</title>
    <script src="index.js"></script>
    <script src="jquery-3.7.1.js"></script>
<body>
<div class="box">box</div>

<script type="text/javascript">

// index.js文件中的$变量与jquery的冲突了
console.log($); // 此时这里就访问不到index.js中的$变量了,也就不打印了

$(function(){
    $('.box').css('color','red');
})


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

问题描述

在上述代码中,index.js文件中有个变量 ,值为 4 ,在 h t m l 中引入了该文件,但是想在 h t m l 访问 i n d e x . j s 中的变量 ,值为4,在html中引入了该文件,但是想在html访问index.js中的 变量 ,值为4,在html中引入了该文件,但是想在html访问index.js中的变量,会发生访问不到,这是由于变量 与 j q u e r y 中 与jquery中 jquery冲突了,那么页面就会以jquery为主,也就是说页面中只会修改box的字体颜色,不会打印4

解决方式

为了解决多个不同的库带来的变量名冲突的问题,jQuery提供了 jQuery.noConflict(); 方式解决了多个库变量名冲突的方法

当使用 jQuery.noConflict(); 后,就会将jquery的 标识符的控制权交给外部文件中的 标识符的控制权交给外部文件中的 标识符的控制权交给外部文件中的,那么此时 就只是一个变量名,也就是说无法用 就只是一个变量名,也就是说无法用 就只是一个变量名,也就是说无法用()的方式来获取dom元素了,所以在使用 jQuery.noConflict();后,要使用闭包的形式,才能解决$()无法获取dom元素的问题。

// jquery提供了一个解决多个库变量名冲突的方法
jQuery.noConflict();
// 使用闭包(自执行函数) 解决 使用jQuery.noConflict();后,无法使用$()的形式操作dom对象的问题
(function($){
    $(function(){
        $('元素id或者class');
    })
})(jQuery)

// 此时$既可以作为变量使用,也可以作为jquery的标识符了(仅在闭包内使用)

完整代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>入口函数</title>
    <script src="index.js"></script>
    <script src="jquery-3.7.1.js"></script>
<body>
<div class="box">box</div>

<script type="text/javascript">

// jquery提供了一个解决多个库变量名冲突的方法
jQuery.noConflict();// 将jquery的$变量的控制权交给index.js

console.log($);

$(function(){
    $('.box').css('color','red');
})


// 使用闭包 解决 将jquery的$变量的控制权交给index.js 后产生的问题
(function($){
    $(function(){
        $('.box').css('color','red');
    })
})(jQuery)


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

基础和层次选择器

jQuery的选择器的作用:选中当前的元素(返回一个jQuery对象)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>基础和层次选择器</title>
    <script src="jquery-3.7.1.js"></script>
<body>
<div class="box">
    <p id="p1">aaa</p>
    <ul>
        <li class="item1">张三</li>
        <li class="item2">李四</li>
        <li class="item3">王五</li>
    </ul>
</div>

<script type="text/javascript">
    // jQuery的选择器的作用:选中当前的元素(返回一个jQuery对象)

    // id选择器
    console.log($('#p1'));

    // class选择器
    console.log($('.class'));

    // 标签选择器
    console.log($('p'));

    // 后代选择器
    console.log($('.box #p1'));
    console.log($('.box li'));

    // 子代选择器
    console.log($('.box>ul>li'));

    // + 选择器(相邻选择器) 获取紧挨着的item1这个li标签的下一个标签
    console.log($('.item1+li'));

    // ~ 选择器(选择器) 除item1这个li标签之外的标签
    console.log($('.item1~li'));

    // 组合选择器 获取p标签,ul标签,li标签
    console.log('p,ul,li')


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

过滤选择器

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>过滤选择器</title>
    <script src="jquery-3.7.1.js"></script>
<body>
<div class="box">
    <p id="p1">aaa</p>
    <p id="p2">bbb</p>
    <ul>
        <li class="item1">张三</li>
        <li class="item2">李四</li>
        <li class="item3">王五</li>
    </ul>
    <input type="text" class="user">
    <input type="password" class="pwd">
</div>

<script type="text/javascript">

    // :first 选择器 第一个元素
    console.log($('ul li:first'));// 获取item1的标签

    // :last 选择器 最后一个元素
    console.log($('ul li:last'));// 获取item3的标签

    //:not('') 除指定的选择器之外
    console.log($('ul li:not(.item2)')); // 获取除.item2外的其他标签

    //:even 获取偶数索引,索引从0开始
    console.log($('ul li:even')); // item1 item3

    //:even 获取奇数索引,索引从0开始
    console.log($('ul li:odd')); // item2


    //:eq(索引) 获取指定索引的元素
    console.log($('ul li:eq(0)'));// 获取ul下的索引为0的元素 也就是item1

    //$().text() 获取指定元素的文本
    console.log($('ul li:eq(0)').text());// 获取ul下的索引为0的元素中文本 也就是王五

    // :gt(索引) 大于索引的元素
     console.log($('ul li:gt(0)').text()); // 李四 王五


    // :lt(索引) 小于索引的元素
      console.log($('ul li:lt(2)').text()); // 张三 李四

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

内容过滤选择器

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>内容过滤选择器</title>
    <script src="jquery-3.7.1.js"></script>
    <style>
        #p1{
            display: none;
        }
    </style>
<body>
<div class="box">
    <p id="p1">aaa</p>
    <p id="p2">bbb</p>
    <ul>
        <li class="item1">
            <h3>张三</h3>
        </li>
        <li class="item2">李四张三</li>
        <li class="item3">王五</li>
        <li id="empty"></li>
        <li id="empty1">
            <h4>hello world</h4>
        </li>
    </ul>
    <input type="text" class="user">
    <input type="password" class="pwd">
</div>

<script type="text/javascript">
    // :contains(文本) 查找包含该文本的所有元素
    console.log($('ul li:contains(张三)')); // item1元素 item2元素

    // :empty 匹配所有不包含子元素或者空文本的元素
    console.log($('ul li:empty')); // 获取到了id为empty的元素

    // :has(标签) 含有选择器所匹配的元素
    console.log($('ul li:has(h4)'));//获取包含h4标签的元素 也就是.empty1

    // .addClass('') 给元素添加class属性
    console.log($('ul li:has(h4)').addClass('a'));

    // :hidden 获取不可见的元素
    console.log($('.box p:hidden')); // 也就是#p1元素

    // :visible 获取可见的元素
    console.log($('.box p:visible')); // 也就是#p2元素
</script>
</body>
</html>

属性选择器

标签[属性=属性值] :获取指定属性值等于属性的标签元素

标签[属性!=属性值] :获取指定属性值不等于属性的标签元素

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>内容过滤选择器</title>
    <script src="jquery-3.7.1.js"></script>
    <style>
        #p1{
            display: none;
        }
    </style>
<body>
<div class="box">
    <p id="p1">aaa</p>
    <p id="p2">bbb</p>
    <ul>
        <li class="item1">
            <h3>张三</h3>
        </li>
        <li class="item2">李四张三</li>
        <li class="item3">王五</li>
        <li id="empty"></li>
        <li id="empty1">
            <h4>hello world</h4>
        </li>
    </ul>
    <input type="text" class="user">
    <input type="password" class="pwd">
</div>

<script type="text/javascript">
    // 属性选择器
    console.log($('input[type=text]')); // 获取type为text的input标签
    
    console.log($('input[type!=password]')); // 获取type不为text的input标签
    
    // input:类型  获取指定类型的input标签
    console.log($('input:text')) // 获取类型为text的input标签


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

判断元素是否存在 或者 是否选中了元素、

// 通过判断元素的长度  $('').length
if($('input[type=text]').length >0){
    alert(111);
}else{
    console('获取元素失败')
}

DOM操作

插入节点

append()方法 和 appendTo()方法

这两个方法是往元素后置添加元素:

$(选择器).append(要添加的元素) :将要添加的元素添加到选中的元素的后面

$(元素1).appendTo(元素2):将元素1的内容追加到元素2的后面,该元素可以是一个选择器

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>append()方法 和 appendTo()方法</title>
    <script src="jquery-3.7.1.js"></script>
<body>

<h3>bbb</h3>
<div class="box"></div>
<script type="text/javascript">
    // 入口函数

    $(function(){
        // $(选择器).append(要添加的元素)
        // 往.box元素中添加元素
        var htmlStr = '<h3>hello world</h3>';
        // $('.box').append(htmlStr);


        // 往.box元素中添加js对象
        var h3Tag = document.createElement('h3');
        h3Tag.innerText = 'aaa';
        // $('.box').append(h3Tag);


        // 往.box元素中添加jQuery对象
        // 案例:将网页中的h3标签移动到.box元素中
        $('.box').append($('h3'));
        
        
        //元素1.appendTo(元素2):将元素1的内容追加到元素2中,该元素可以是一个选择器
        // 使用appendTo方法,后面可以直接跟上.css()或者.click()等其他方法,非常方便

        // 1.使用appendTo将 '<h4>老村长</h4>' 添加到 .box元素中
        $('<h4>老村长</h4>').appendTo('.box');

        // 2.使用appendTo将 '<h4>老村长</h4>' 添加到 .box元素中,并且设置css样式
        $('<h4>老村长</h4>').appendTo('.box').css('color','green');

        // 3.使用appendTo将 '<h4>老村长</h4>' 添加到 .box元素中,并且设置css样式 以及 点击事件
        $('<h4>老村长</h4>').appendTo('.box').css('color','green').click(function(){
            // 会发现这里的this指向了dom节点对象,显然不如我们的意
            console.log(this);
            // 使用 $(this) 方式强制转成 jquery对象
            console.log($(this).text()); //强制转换后,获取文本 老村长
        });


    })

</script>
</body>
</html>
prepend()方法 和 prependTo()方法

这两个方法是往元素前置添加元素:

$(选择器).prepend(要添加的元素) :将要添加的元素添加到选中的元素的前面

$(元素1).prependTo(元素2):将元素1的内容追加到元素2的前面,该元素可以是一个选择器

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>prepend()方法 和 prependTo()方法</title>
    <script src="jquery-3.7.1.js"></script>
<body>

<div class="box">
    <span>参考点</span>
</div>


<script type="text/javascript">
    // 入口函数

    $(function(){

        //$().prepend() 往选中的元素前面添加元素 
        $('.box').prepend('<a herf="#">百度一下1</a>');
        // $().prependTo('选择器') 将内容添加到选中的元素的前面
        $('<a herf="#">百度一下2</a>').prependTo('.box');
    })

</script>
</body>
</html>
after()方法和insertAfter()方法

这两个方式也是插入元素的方法,与 append()方法 和 appendTo()方法 以及 prepend()方法 和 prependTo()方法 方法类似,区别在于这两个方式是在同级元素来进行插入的操作,而前面的方法是在元素中操作,换句话来说,就是插入子节点

$(选择器).after(要添加的内容) :在 选中的元素 后面 添加 内容

$(‘内容’).insertAfter(‘选择器’) :将 要添加的内容 添加到 选中元素 的后面

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>after()方法和insertAfter()方法</title>
    <script src="jquery-3.7.1.js"></script>
<body>

<h3>h3标签</h3>

<div class="box"></div>


<script type="text/javascript">
    // 入口函数

    $(function(){

        //$(选择器).after(要添加的内容)
        // 在h3标签后面添加  <h1>h1标签</h1>
        $('h3').after('<h1>h1标签</h1>');

        //$('内容').insertAfter('选择器')
        // 将 <h2>h2标签</h2> 添加到h1标签的前面
        $('<h2>h2标签</h2>').insertAfter('h1');


    })

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

删除节点

删除节点有两种方法,一个是remove,一个是detach

$(选择器).remove() :既删除节点,又删除节点上的绑定事件

$(选择器).detach() : 只删除节点,不删除绑定事件

remove方法
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>删除节点--remove方法</title>
    <script src="jquery-3.7.1.js"></script>
<body>
<div class="box"></div>
<div class="wrap">
    <button>按钮</button>
</div>
<script type="text/javascript">
    // 入口函数
    $(function(){
        // 删除节点: $().remove() 会返回一个jquery对象
        // 既删除节点,又删除节点上的绑定事件
        $('button').click(function(){
           $(this).remove(); // 删除了button按钮

</script>
</body>
</html>
detach方法
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>删除节点--detach方法</title>
    <script src="jquery-3.7.1.js"></script>
<body>
<div class="box"></div>
<div class="wrap">
    <button>按钮</button>
</div>
<script type="text/javascript">
    // 入口函数
    $(function(){
        // 删除节点: $().detach()
        // 只删除节点,不删除绑定事件
        $('.wrap button').click(function(){
            $(this).detach(); // 删除了button按钮
        })

</script>
</body>
</html>
reomove与detach的区别

做个小案例看看这两者方法的区别

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>remove与detach的区别</title>
    <script src="jquery-3.7.1.js"></script>
<body>

<h3>h3标签</h3>

<div class="box">
    <h4>h4标签</h4>
</div>

<div class="wrap">
    <button>按钮</button>
</div>

<h2>h2标签</h3>


<script type="text/javascript">
    // 入口函数
    $(function(){
        // =======================1.用remove方法删除节点========================
        $('button').click(function(){
            // 既删除节点,又删除节点上的绑定事件
            var btnJq = $(this).remove(); // 返回一个jquery对象
            $('.box').prepend(btnJq); // 将删除后返回的jquery对象添加到.box元素中
        })
        
        
        // ======================2.用detach方法删除节点===========
        $('button').click(function(){
            // 只删除节点,不删除绑定事件
            var btnJq = $(this).detach(); // 返回一个jquery对象
            $('.box').prepend(btnJq); // 将删除后返回的jquery对象添加到.box元素中
        })
        
             
        /*
        	案例效果是:原本的button按钮在class为wrap的标签中,当点击button按钮的时候,用remove方法将.wrap中的button按钮删除,此时会返回一个被被删除的元素jquery对象,再将此对象添加到.box的元素中。
        	可以发现,原本button具有点击事件,但是被删除后,再重新点击,就没有了点击事件,而如果使用detach的方式删除节点,就会发现虽然节点被删除了,但是节点绑定的事件还存在
        	这便是与reomve()和detach()方法的区别
        
        */


    })
</script>
</body>
</html>
清空节点
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>清空节点</title>
    <script src="jquery-3.7.1.js"></script>
<body>

<h3>h3标签</h3>
<div class="box"><h4>h4标签</h4></div>
<div class="wrap"><button>按钮</button></div>
<h2>h2标签</h3>
<script type="text/javascript">
    // 入口函数
    $(function(){
        $('button').click(function(){
            // 1.清空节点: empty()
            $('.box').empty(); // 将.box中的元素清空
            
			// 2.将节点制空,变相的清空节点
            $('box').html('');// 将.box中的html元素置空,也可以清空元素

  })
</script>
</body>
</html>

复制节点

复制节点也称为克隆节点

clone方法

$(选择器).clone(布尔值)

clone的默认值为false,也就是只复制元素,当值改为true的时候,就会复制元素和事件

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>复制节点</title>
    <script src="jquery-3.7.1.js"></script>
<body>

<div class="clone">
    <ul>
        <li>小马哥</li>
    </ul>
</div>

<script type="text/javascript">
    // 入口函数

    $(function(){
        // clone(布尔值) 克隆元素
        // clone的默认值为false,也就是只复制元素,当值改为true的时候,就会复制元素和事件
        $('.clone ul li').click(function(){
            $(this).clone().appendTo('.clone ul'); // 只复制元素
            // $(this).clone(true).appendTo('.clone ul'); // 复制元素 和绑定事件
        })

    })

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

替换节点

replaceWith()方法和replaceAll()方法

$().replaceWith(‘要替换的元素’)

$(‘要替换的元素’).replaceAll(‘选择器’)

其实这两种替换方式,效果是一样的,就是写法不一样

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>替换节点</title>
    <script src="jquery-3.7.1.js"></script>
<body>
<div class="replace">
    <p>hello</p>
    <p>world</p>
</div>

<script type="text/javascript">
    // 入口函数
    $(function(){

        // 1.替换节点: $().replaceWith('要替换的元素')
        $('.replace p').replaceWith('<i>hello</i>')

        // 2.替换节点: $('要替换的元素').replaceAll('选择器')
        $('<i>hello</i>').replaceAll('p')
        // 其实上面的两种替换方式,结果都是将所有p标签的元素全部替换成斜体的hello,效果都一样

    })//入口函数结尾

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

包裹节点

wrap()包裹节点

$(‘选择器’).wrap(‘包裹元素’) :将 选中的内容 用 包裹元素 进行包裹

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>包裹节点</title>
    <script src="jquery-3.7.1.js"></script>
<body>

<div class="replace">
    <p>hello</p>
    <p>world</p>
</div>

<script type="text/javascript">
    // 入口函数

    $(function(){
        // 1.包裹节点: $('选择器').wrap('包裹元素')
        // 将 选中的内容 用 包裹元素 进行包裹
        $('.replace p').wrap('<div class="box2"></div>');

    })//入口函数结尾

</script>
</body>
</html>
unwrap() 删除包裹节点

$(‘选择器’).unwrap() : 删除选中内容的包裹节点

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>包裹节点</title>
    <script src="jquery-3.7.1.js"></script>
<body>
<div class="replace">
    <p>hello</p>
    <p>world</p>
</div>
<script type="text/javascript">
    // 入口函数
    $(function(){
        // 2.删除包裹节点:$('选择器').unwrap()
        $('.replace p').unwrap();

    })//入口函数结尾

</script>
</body>
</html>
wrapInner() 包裹标签

$(‘选择器’).wrapInner(包裹标签) : 将选取到的元素的子元素,用指定包裹包起来

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>包裹节点</title>
    <script src="jquery-3.7.1.js"></script>
<body>
<div class="replace">
    <p>hello</p>
    <p>world</p>
</div>
<script type="text/javascript">
    // 入口函数
    $(function(){
        // $('选择器').wrapInner(包裹标签) 
        // 取到当前的p标签的子内容,用指定标签包裹起来
        // 效果:将所有段落内的每子内容加粗
        $('.replace p').wrapInner('<strong></strong>')

    })//入口函数结尾

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

属性操作attr()

设置属性值

1.设置单个属性值:$(‘选择器’).attr(‘属性’,‘属性值’)

2.设置多个属性值: $(‘选择器’).attr({‘属性1’:‘属性值1’,‘属性2’:‘属性值2’,…})

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>设置属性值</title>
    <script src="jquery-3.7.1.js"></script>
    <style>
        #box{
            width: 200px;
            height: 200px;
            border: 1px solid red;
        }
    </style>
<body>

<div></div>
<span></span>

<script type="text/javascript">
    // 入口函数
    $(function(){
        // 1.设置单个属性值:$().attr('属性','属性值')
        // 给div标签设置id为box
        $('div').attr('id','box');

        // 2.设置多个属性值: $().attr({'属性1':'属性值1','属性2':'属性值2',....})
        // 给span设置id为sp,title为盒子
        $('span').attr({'id':'sp','title':'盒子'});
    })//入口函数结尾

</script>
</body>
</html>
获取属性值

获取属性值:$(‘选择器’).attr(‘属性’)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>获取属性值</title>
    <script src="jquery-3.7.1.js"></script>
    <style>
        #box{
            width: 200px;
            height: 200px;
            border: 1px solid red;
        }
    </style>
<body>
<div name='b' class="active"></div>
<script type="text/javascript">
    // 入口函数
    $(function(){
        // 3.获取属性值:$().attr('属性')
        // 获取div标签的name属性的值
        console.log($('div').attr('name'));

    })//入口函数结尾

</script>
</body>
</html>
属性操作应用

attr的应用:两秒之后给页面添加图片

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>属性操作应用</title>
    <script src="jquery-3.7.1.js"></script>
    <style>
        #box{
            width: 200px;
            height: 200px;
            border: 1px solid red;
        }
    </style>
<body>
<img src="" alt="">
<script type="text/javascript">
    // 入口函数
    $(function(){
        // attr的应用:两秒之后给页面添加图片
        setTimeout(function(){
            $('img').attr({
                src:'https://img0.baidu.com/it/u=1053269014,1961200268&fm=253&app=138&size=w931&n=0&f=PNG&fmt=auto?sec=1722790800&t=99c3601d66f930ecc4ac405709343fa7',
                alt:'图片'
            })
        },2000);

    })//入口函数结尾
</script>
</body>
</html>

类操作

添加类

$(‘选择器’).addClass() : 给选中元素添加class属性

// 1.$('选择器').addClass() 给选中元素添加class属性
$('.box').click(function(){
    $(this).addClass('active');
})
添加多个类

添加多个类:$(‘选择器’).addClass(类1 类2 类3)

// 添加多个类:$('选择器').addClass(类1 类2 类3)
$(this).addClass('activ a b');
移除类

$(‘选择器’).removeClass():给选中元素移除class属性

// 2.$('选择器').removeClass() 给选中元素移除class属性
$('.box').click(function(){
    $(this).removeClass('active');
})
判断是否含有类

$(‘选择器’).hasClass():判断选中的元素是否有 指定的类

// 3.$('选择器').hasClass() 判断选中的元素是否有 指定的class属性 有返回true 没有返回false
// $('.box').hasClass('active')
console.log($('.box').hasClass('active'));
切换类

$(‘选择器’).toggleClass(‘class类’) :如果有指定的class类就移除,没有就添加

//切换类:$('选择器').toggleClass('class类') 如果有指定的class类就移除,没有就添加
$('.box').toggleClass('active');

完整代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>类操作</title>
    <script src="jquery-3.7.1.js"></script>
    <style>
       .box{
            width: 200px;
            height: 200px;
            background-color: red;
       }
       .active{
            background-color: green;
       }
    </style>
<body>

<div class="box"></div>


<script type="text/javascript">
    // 入口函数
    $(function(){
        // 1.$('选择器').addClass() 给选中元素添加class属性
        $('.box').click(function(){
            $(this).addClass('active');
        })

        // // 2.$('选择器').removeClass() 给选中元素移除class属性
        // $('.box').click(function(){
        //     $(this).removeClass('active');
        // })

        // 3.$('选择器').hasClass() 判断选中的元素是否有 指定的class属性 有返回true 没有返回false
        console.log($('.box').hasClass('active'));

        // 添加多个类:$('选择器').addClass(类1 类2 类3)
        $(this).addClass('activ a b');

        //切换类:$('选择器').toggleClass('class类') 如果有指定的class类就移除,没有就添加
        $('.box').toggleClass('active');

    })//入口函数结尾

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

值操作

html()方法

$().html() :获取html中的值 既能获取文本有获取html

$().html(html内容):设置或修改html中的值

// 1.$().html() :获取html中的值 既能获取文本有获取html
console.log($('#content ul li:first').html());// 此时就会打印第一个li标签的元素

// 2.$().html(`html内容`):设置或修改html中的值
$('#content ul li:first').html(
    `<img src="" alt="">
    <p>小马哥</p>
    <h3>这是h3标签</h3>
    `);
text()方法

$().text():获取标签中的文本 仅仅获取文本

// 3.$().text():获取标签中的文本 仅仅获取文本
$('#content ul li:first').text();
val()方法

$().val(): 获取元素的值

$().val(‘设置值’): 设置元素的值

注意:当.val()方法针对于输入框的时候,是获取值或者设置值,但是针对于下拉框,单选框,多选框的时候就是设置选中值,当想要选中多个值的时候,可以用$(‘选择器’).val([‘默认值1’,‘默认值2’,…]) ,选中值得是value属性的属性值

// 4.$().val(): 获取文本输入框的值
$('input[type=text]').val();

// 5.$().val('要设置的值') :设置输入框的值
$('input[type=text]').val('设置输入的值');

完整代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>值操作</title>
    <script src="jquery-3.7.1.js"></script>
    <style>
    </style>
<body>

<div id="content">
    <ul>
        <li>
            <img src="" alt="">
            <p>小马哥</p>
        </li>
    </ul>
    <input type="text" value="文本框">
    <select name="" id="single">
        <option>苹果</option>
        <option>香蕉</option>
    </select>
        <select name="" id="multiple" multiple>
        <option selected>苹果</option>
        <option>香蕉</option>
        <option selected>橘子</option>
    </select>

    <input type="checkbox" value="a">A
    <input type="checkbox" value="b">B
    <input type="radio" value="1"><input type="radio" value="0"></div>


<script type="text/javascript">
    // 入口函数
    $(function(){
        // 1.$().html() :获取html中的值 既能获取文本有获取html
        $('#content ul li:first').html();
        console.log($('#content ul li:first').html());// 此时就会打印第一个li标签的元素

        // 2.$().html(`html内容`):设置或修改html中的值
         $('#content ul li:first').html(
            `<img src="" alt="">
            <p>小马哥</p>
            <h3>这是h3标签</h3>
            `);


         // 3.$().text():获取标签中的文本 仅仅获取文本
         console.log($('#content ul li:first').text());

         // 4.$().val(): 获取文本输入框的值
         $('input[type=text]').val()
         console.log($('input[type=text]').val());

         // 5.$().val('要设置的值') :设置输入框的值
         $('input[type=text]').val('设置输入的值');

         // 直接选中 下拉框指定的内容
         $('#single').val('香蕉');

         // 直接选中单个值 下拉框中的香蕉和橘子
         $('#multiple').val(['香蕉','橘子']);

         // 直接选中多个值,给input标签设置值的时候,要使用value值
         $('input').val(['b','0']);

    })//入口函数结尾

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

筛选方法

children()方法

$(‘选择器’).children() 获取匹配元素的子元素集合

// children() 获取匹配元素的子元素集合
console.log($('.box').children()); // 输出.box中的子元素集合
next()方法

$(‘选择器’).next() 获取匹配元素后面紧邻的同级元素

//next() 获取匹配元素后面紧邻的同级元素
console.log($('.box').next()); // 打印.box2对象
parent()方法

$(‘选择器’).parent() 获取父级元素

// parent() 获取父级元素
console.log($('ul li').parent());// 打印ul标签
parents()方法

$(‘选择器’).parents() 获取元素的祖先辈们

// parents() 获取元素的祖先辈们 从选中元素一直往上找父类,直到找到html为止
console.log($('ul li').parents());// 打印ul标签的所有父级元素
prev()方法

$(‘选择器’).prev() 获取匹配元素前面紧邻的同级元素

//prev() 获取匹配元素前面紧邻的同级元素
console.log($('.box2').prev()); // 打印.box对象
eq()方法

$(‘选择器’).eq(元素下标) 获取指定下标的元素 等同于 $(‘:eq()’)

// eq(元素下标) 获取指定下标的元素 等同于 $(':eq()')
console.log($('ul li').eq(2)[0]); //打印下标为2的li标签

完整代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>筛选方法</title>
    <script src="jquery-3.7.1.js"></script>
    <style>
    </style>
<body>


<div class="box">
    <p>aaa</p>
    <p>bbb</p>
    <ul>
        <li>ccc</li>
        <li>ddd</li>
        <li>eee</li>
        <li>fff</li>
        <li>ggg</li>
    </ul>
</div>

<div class="box2"></div>
<div class="box3"></div>


<script type="text/javascript">
// 入口函数
$(function(){
    // children() 获取匹配元素的子元素集合
    console.log($('.box').children()); // 输出.box中的子元素集合

    //next() 获取匹配元素后面紧邻的同级元素
    console.log($('.box').next()); // 打印.box2对象

    // parent() 获取父级元素
    console.log($('ul li').parent());// 打印ul标签

    // parents() 获取元素的祖先辈们 从选中元素一直往上找父类,直到找到html为止
    console.log($('ul li').parents());// 打印ul标签的所有父级元素

    //prev() 获取匹配元素前面紧邻的同级元素
    console.log($('.box2').prev()); // 打印.box对象

    // eq(元素下标) 获取指定下标的元素 等同于 $(':eq()')
    console.log($('ul li').eq(2)[0]); //打印下标为2的li标签

})//入口函数结尾

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

siblings()方法

siblings(‘标签选择器’) 方法:获取除当前对象之外的其他元素

下面做两个案例来查看该方法的具体应用,实现效果,页面上有多个button按钮,当点击其中一个按钮,被点击的按钮颜色就变红,其他按钮保持白色

案例1:没有嵌套标签

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>siblings方法的应用</title>
    <script src="jquery-3.7.1.js"></script>
    <style>
        button{
            background: #fff;
        }
    </style>
<body>

<button>按钮1</button>
<button>按钮2</button>
<button>按钮3</button>
<button>按钮4</button>
<button>按钮5</button>

<script type="text/javascript">
// 入口函数
$(function(){
    // siblings('标签选择器') 方法的应用
    // 获取除当前对象之外的其他元素

    $('button').click(function(){
        // 这里必须要用$(this),不能用this,因为this指向的是标签,要用$(this)的方式强制转为jquery对象,然后才能进行下一步操作
        $(this).css('background-color','red').siblings('button').css('background-color','#fff');

        /*
            上面的代码解释:$(this)获取当前被点击的对象,然后给该对象修改了css,同时用.siblings('button')的方式选择 除 当前被点击的button对象 之外 的其他 button按钮对象 给修改css样式

        */

    })

})//入口函数结尾

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

案例2:嵌套标签

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>siblings方法的应用</title>
    <script src="jquery-3.7.1.js"></script>
    <style>
        button{
            background: #fff;
        }
    </style>
<body>

<ul>
    <li><button>按钮1</button></li>
    <li><button>按钮2</button></li>
    <li><button>按钮3</button></li>
    <li><button>按钮4</button></li>
    <li><button>按钮5</button></li>
</ul>

<script type="text/javascript">
// 入口函数
$(function(){
    // siblings('标签选择器') 方法的应用
    // 获取除当前对象之外的其他元素
        $(this).css('background-color','red').parent().siblings('li').children().css('background-color','#fff');
        
        /*
            上面的代码解释:针对于嵌套标签,$(this)获取当前被点击的对象,然后给该对象修改了css,此时被选中的是li标签下的button,接着获取当前元素的父类元素,也就是获取li标签,接着用.siblings('li')获取除当前元素父类li的其他父类元素li,然后再通过每一个li标签获取每一个子类元素,也就是每一个li标签下的button,然后再设置css样式

        */

    })

})//入口函数结尾

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

css的DOM方法

css()方法

1.$(‘选择器’).css(‘属性’) 获取属性值

2.$(‘选择器’).css(‘属性’,‘属性值’) 设置单个属性值

3.$(‘选择器’).css({‘属性1’:‘属性值1’,‘属性2’:‘属性值2’,…})

// 1.$('选择器').css('属性') 获取属性值
console.log($('.box').css('color'));

// 2.$('选择器').css('属性','属性值') 设置单个属性值
$('.box').css('color','red');

// 3.$('选择器').css({'属性1':'属性值1','属性2':'属性值2',...}) 设置多个属性值
$('.box').css({
    'color':'red',
    'font-size':20
})
offset()方法

$(‘选择器’).offset() 获取元素在当前视图的相对便宜量,会返回一个对象,包含top值和left值,不会受边框或者其他属性的影响

// 4.$('选择器').offset() 获取元素在当前视图的相对便宜量,会返回一个对象,包含top值和left值,不会受边框或者其他属性的影响
var offset = $('p').offset();
console.log(offset.top);
console.log(offset.left);
scrollTop()方法

$(‘选择器’).scrollTop() 获取页面向下滚动的距离

// 监听页面的滚动事件
$(window).scroll(function(){
    // 5.$('选择器').scrollTop() 获取页面向下滚动的距离
    console.log($(this).scrollTop());

})

完整代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>css的DOM方法</title>
    <script src="jquery-3.7.1.js"></script>
    <style>
        *{
            margin: 0;
            padding: 0;
        }
        p{
            width: 200px;
            height: 200px;
            background-color: yellow;
            position: absolute;
            top: 1000px;
            left: 100px;
        }
    </style>
<body>

<div class="box">
    <p>aaa</p>
</div>


<script type="text/javascript">
// 入口函数
$(function(){
    // 1.$('选择器').css('属性') 获取属性值
    console.log($('.box').css('color'));

    // 2.$('选择器').css('属性','属性值') 设置单个属性值
    $('.box').css('color','red');

    // 3.$('选择器').css({'属性1':'属性值1','属性2':'属性值2',...}) 设置多个属性值
    $('.box').css({
        'color':'red',
        'font-size':20
    })

    // 4.$('选择器').offset() 获取元素在当前视图的相对便宜量,会返回一个对象,包含top值和left值,不会受边框或者其他属性的影响
    var offset = $('p').offset();
    console.log(offset.top);
    console.log(offset.left);

    // 监听页面的滚动事件
    $(window).scroll(function(){
        // 5.$('选择器').scrollTop() 获取页面向下滚动的距离
        console.log($(this).scrollTop());

    })

})//入口函数结尾

</script>
</body>
</html>
width()方法

1.$(‘选择器’).width()获取选中元素的宽度,是一个数值

2.$(‘选择器’).width(值) 设置选中元素的宽度

以上这两个方法均只获取元素的width值

// width() 包含元素的width
// $('选择器').width()获取选中元素的宽度,是一个数值
$('.box').width();

//$('选择器').width(值) 设置选中元素的宽度
$('.box').width(300);
height()方法

$(‘选择器’).height()获取选中元素的高度,是一个数值

// height() 包含元素的height
// $('选择器').height()获取选中元素的高度,是一个数值
$('.box').height();
innerWidth() 和 innerHeight()方法

获取元素的 width + padding,是一个数值

// 包含元素的 width + padding
$('.box').innerWidth();
$('.box').innerHeight();
outerWidth() 和 outerHeight()方法

获取元素的 width + padding + border 是一个数值

// 包含元素的 width + padding + border
$('.box').outerWidth();
$('.box').outerHeight();

完整代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>盒子宽高</title>
    <script src="jquery-3.7.1.js"></script>
    <style>
        .box{
            width: 200px;
            height: 200px;
            background: red;
            border: 2px solid #000;
            padding: 50px;
        }
    </style>
<body>

<div class="box"></div>
<script type="text/javascript">
// 入口函数
$(function(){

   // width() 包含元素的width
   // $('选择器').width()获取选中元素的宽度,是一个数值
   $('.box').width();
   //$('选择器').width(值) 设置选中元素的宽度
   $('.box').width(300);

   // height() 包含元素的height
   // $('选择器').height()获取选中元素的高度,是一个数值
   $('.box').height();

   // 包含元素的 width + padding
   $('.box').innerWidth();
   $('.box').innerHeight();

   // 包含元素的 width + padding + border
   $('.box').outerWidth();
   $('.box').outerHeight();


})//入口函数结尾

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

事件

鼠标事件

常用事件
click():鼠标单击事件
dblclick():鼠标双击事件(不常用)
mousedown()/mouseup() :鼠标按下/鼠标抬起事件
mousemove() :鼠标移动事件(不常用)
mouseover()/mouseout() :鼠标移入/移出事件
mouseenter()/mouseleave() : 鼠标进入/离开 事件 (推荐使用)
focus()/blur():鼠标聚焦/失焦事件
keydown()/keyup():键盘

ready():文档加载事件
scroll():监听窗口事件

鼠标点击事件
$('#box').click(function(){
    alert($(this).text());// 打印#box的文本

    //$('选择器').hide(毫秒,[回到函数,可选])
    $(this).hide();// 隐藏#div
})
鼠标双击事件
// 2.dblclick 鼠标双击事件 鼠标两次点击事件的时间差是300ms
$('#box').dblclick(function(){
    console.log('双击了');
})
鼠标按下事件
// 3.mousedown 鼠标按下事件
$('#box').mousedown(function(){
    console.log('鼠标按下了');
})
鼠标抬起事件
// 4.mouseup 鼠标抬起事件
$('#box').mouseup(function(){
    console.log('鼠标抬起了');
})
鼠标移动事件
//5.mousemove 鼠标移动事件
$('#box').mousemove(function(){
    console.log('鼠标移动了');
})

完整代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>鼠标事件</title>
    <script src="jquery-3.7.1.js"></script>
    <style>
    </style>
<body>

<div id="box" style="width: 200px;height: 200px;background:red;">
aaa
</div>


<script type="text/javascript">
// 入口函数
$(function(params){
    // 1.click 鼠标点击事件
    $('#box').click(function(){
        alert($(this).text());// 打印#box的文本

        //$('选择器').hide(毫秒,[回到函数,可选])
        $(this).hide();// 隐藏#div
    })


    // 2.dblclick 鼠标双击事件 鼠标两次点击事件的时间差是300ms
    $('#box').dblclick(function(){
        console.log('双击了');
    })

    // 3.mousedown 鼠标按下事件
    $('#box').mousedown(function(){
        console.log('鼠标按下了');
    })

    // 4.mouseup 鼠标抬起事件
    $('#box').mouseup(function(){
        console.log('鼠标抬起了');
    })

    //5.mousemove 鼠标移动事件
    $('#box').mousemove(function(){
        console.log('鼠标移动了');
    })


})//入口函数结尾

</script>
</body>
</html>
鼠标穿过事件

1.mouseover()/mouseout():鼠标穿过被选元素或者当前选中元素的子元素

2.mouseover()/mouseout():鼠标只穿过被选元素,推荐使用

mouseover()/mouseout() 方法

// 1.mouseover()/mouseout():鼠标穿过被选元素或者当前选中元素的子元素

$('#box').mouseover(function(){
    console.log('鼠标穿过了');
})


$('#box').mouseout(function(){
    console.log('鼠标离开了');
})

mouseover()/mouseout()方法

// 2.mouseover()/mouseout():鼠标只穿过被选元素,推荐使用

// 当元素之间存在缝隙的时候,用 mouseover()/mouseout() 更好
$('.box').mouseenter(function(){
    // $('.content').show();

    // 使用动画的时候,先要停止动画, 再开启动画
    $('.content').stop().slideDown();
})

$('.box').mouseleave(function(){
    // $('.content').hide();

    // 使用动画的时候,先要停止动画, 再开启动画
    $('.content').stop().slideUp();
})

完整代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>鼠标穿过事件</title>
    <script src="jquery-3.7.1.js"></script>
    <style>
        .box{
            width: 100px;
            height: 40px;
            background-color: bisque;
            position: absolute;
        }
        .box .content{
            position: absolute;
            width: 200px;
            height: 200px;
            top: 40px;
            background-color : red;
            display: none;
        }
    </style>
<body>

<div id="box" style="width: 200px;height: 200px;background:red;">
    <p style="background: green">aaa</p>
</div>


<div class="box">
    <div class="content"></div>
</div>


<script type="text/javascript">
// 入口函数
$(function(params){
    // 1.mouseover()/mouseout():鼠标穿过被选元素或者当前选中元素的子元素
   
    $('#box').mouseover(function(){
        console.log('鼠标穿过了');
    })


    $('#box').mouseout(function(){
        console.log('鼠标离开了');
    })


    // 2.mouseover()/mouseout():鼠标只穿过被选元素,推荐使用

    // 当元素之间存在缝隙的时候,用 mouseover()/mouseout() 更好
    $('.box').mouseenter(function(){
        // $('.content').show();

        // 使用动画的时候,先要停止动画, 再开启动画
        $('.content').stop().slideDown();
    })

    $('.box').mouseleave(function(){
        // $('.content').hide();

        // 使用动画的时候,先要停止动画, 再开启动画
        $('.content').stop().slideUp();
    })



})//入口函数结尾

</script>
</body>
</html>
鼠标焦点事件

$().focus() 聚焦事件

$().blur() 失焦事件

$().keydown() 键盘按下

focus()方法

// 1.$().focus() 聚焦事件
$('input[type=text]').focus(function(){
    console.log('获取焦点了');
})

blur()方法

// 2.$().blur() 失焦事件
$('input[type=text]').blur(function(){
    console.log('失去焦点了');
})

keydown()方法

// keydown() 键盘按下
$(window).keydown(function(event){
    // event 中的keyCode可以获取到按下的键,是ASCII形式
    console.log('键盘按下了');
    console.log(event.keyCode);

})

完整代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>鼠标焦点事件</title>
    <script src="jquery-3.7.1.js"></script>
<body>
<input type="text">
<script type="text/javascript">
// 入口函数
$(function(params){
   // focus()/blur() :鼠标聚焦/失焦事件

    // 1.$().focus() 聚焦事件
    $('input[type=text]').focus(function(){
        console.log('获取焦点了');
    })

    // 2.$().blur() 失焦事件
    $('input[type=text]').blur(function(){
        console.log('失去焦点了');
    })

    // 无法使用输入框
     $('input[type=text]').blur(function(){
        // 这用的是js中的方法
        this.blur();
    })

     // keydown() 鼠标按下
     $(window).keydown(function(event){
        // event 中的keyCode可以获取到按下的键,是ASCII形式
        console.log('键盘按下了');
        console.log(event.keyCode);

     })
})//入口函数结尾

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

表单事件

表单常用方法:
1. ( ) . c h a n g e ( ) : 当元素的值发生改变时触发 c h a n g e 事件,仅仅适用于文本域 ( t e x t a r e a s e l e c t i n p u t ) 2. ().change() : 当元素的值发生改变时触发change事件,仅仅适用于文本域 (textarea select input) 2. ().change():当元素的值发生改变时触发change事件,仅仅适用于文本域(textareaselectinput)2.().select()
3.$().submit() :表单提交事件

change()方法
// $().change() 当失去焦点的时候触发change事件,仅仅适用于文本域 (textarea select input)
$('input[type=text]').change(function(){
    console.log('值发生了变化');
    // 获取输入框的内容
    console.log($(this).val());
})

// 针对于 select标签的 change()方法
$('#select').change(function(){
    // 当选中select的时候,就获取选中的值
    console.log($(this).val());
})
submit()方法
// $().submit() 表单提交事件
$('form').submit(function(event){
    // 阻止默认行为:event.preventDefault()
    alert('aaa')
    console.log('111');

    // 获取form表单中的输入框以及下拉框的选中内容
    var val = $('input[type=text]').val();
    var oVal = $('#select').val();
    console.log(val,oVal);
})

完整代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>表单事件</title>
    <script src="jquery-3.7.1.js"></script>
<body>

<form action="">
    <input type="text">
    <select name="" id="select">
        <option value="a">a</option>
        <option value="b">b</option>
    </select>
    <input type="submit">
</form>



<script type="text/javascript">
// 入口函数
$(function(params){
    /*
    表单常用方法:
        change() : 当元素的值发生改变时
        select()
        submit()
    */


    // $().change() 当失去焦点的时候触发change事件,仅仅适用于文本域 (textarea select input)
    $('input[type=text]').change(function(){
        console.log('值发生了变化');
        // 获取输入框的内容
        console.log($(this).val());


    })

    // 针对于 select标签的 change()方法
    $('#select').change(function(){
        // 当选中select的时候,就获取选中的值
        console.log($(this).val());
    })


    // $().submit() 表单提交事件
    $('form').submit(function(event){
        // 阻止默认行为:event.preventDefault()
        alert('aaa')
        console.log('111');

        // 获取form表单中的输入框以及下拉框的选中内容
        var val = $('input[type=text]').val();
        var oVal = $('#select').val();
        console.log(val,oVal);
    })


})//入口函数结尾

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

冒泡事件

再给父类和子类元素绑定事件的时候,一定要阻止冒泡

阻止冒泡行为:

event.stopPropagation()

return false

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>事件冒泡</title>
    <script src="jquery-3.7.1.js"></script>
    <style>
        .box{
            width: 200px;
            height: 200px;
            border: 1px solid red;
        }
    </style>
<body>

<div class="box">
    <h3>冒泡</h3>
</div>


<script type="text/javascript">
// 入口函数
$(function(params){
    // 当点击父元素,提示框显示 父元素点击了
    $('.box').click(function(){
        alert('父元素点击了');
        // return false;//也可以阻止冒泡行为
    })

    // 由于冒泡事件的影响,当点击子元素,提示框显示 子元素点击了,父元素点击了
    $('h3').click(function(event){
        // event.stopPropagation(); // 阻止冒泡行为
        alert('子元素点击了');
    })


    $(document).click(function(){
        alert('文档被点击了');
    })

    // 总结:所以再给父类和子类元素绑定事件的时候,一定要阻止冒泡

})//入口函数结尾

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

冒泡事件应用

切换颜色的案例

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>冒泡应用</title>
    <script src="jquery-3.7.1.js"></script>
    <style>
        *{
            padding: 0;
            margin: 0;
        }
        .slideDownView{
            width: 100%;
            height: 400px;
            background-color: aqua;
            position: fixed;
            top: 0;
            left: 0;
            display: none;
        }
        .slideDownView ul li{
            display: inline-block;
            width: 100px;
            height: 40px;
            background-color: blueviolet;
            color: #fff;
            list-style: 40px;
            text-align: center;
        }

        .slideDownView ul li a{
            display: block;
            width: 100px;
            height: 40px;
            color: #fff;
        }
    </style>
<body>

<a href="#" class="changefu">换肤</a>
<div class="slideDownView">
    <ul>
        <li><a href="#">热门</a></li>
        <li><a href="#">游戏</a></li>
        <li><a href="#">美女</a></li>
    </ul>
</div>


<script type="text/javascript">
// 入口函数
$(function(){
    $('.changefu').click(function(){
        // 阻止a标签的默认行为
        event.preventDefault();
        // 阻止冒泡行为
        event.stopPropagation();
        // 下拉动画
        $('.slideDownView').stop().slideDown(500);

        $('.slideDownView ul li a').click(function(event){
            // 阻止a标签的默认行为
            event.preventDefault();
            // 阻止冒泡行为
            event.stopPropagation();
            $(this).css('color','red').parent().siblings('li').children().css('color','#fff');
        })

    })

    $('slideDownView,ul').click(function(){
        // 阻止冒泡的事件
        return false;
    })

    $(document).click(function(){
        // 上拉动画
        $('.slideDownView').stop().slideUp(500);
    })


})//入口函数结尾

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

事件代理

事件代理 将子类的事件绑定到父类上,原理:利用冒泡的原理,将事件加到父级上,触发执行结果

$().on(‘事件’,‘要绑定事件的元素’,回调函数) 可以给新创建的元素也绑定事件,而click方法只能给原本存在的元素绑定事件,所以说on方法更加的推荐使用

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>事件代理</title>
    <script src="jquery-3.7.1.js"></script>
    <style>
        
    </style>
<body>

<ul>
    <li>博客内容1</li>
</ul>
<script type="text/javascript">
// 入口函数
$(function(){
    // 事件代理 将子类的事件绑定到父类上
    // 原理:利用冒泡的原理,将事件加到父级上,触发执行结果


    // $().on('事件','要绑定事件的元素',回调函数) 可以给新创建的元素也绑定事件,而click方法只能给原本存在的元素绑定事件,所以说on方法更加的推荐使用
    $('ul li').on('click','li',function(){
        alert($(this).text());
    })

    // 模拟 将来做的事件
    setTimeout(function(){
        $('<li>博客内容2</li>').append('ul');
    })
    

})//入口函数结尾

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

合成事件

jquery 中有两个合成事件,hover() 事件 和 toggle()事件
$().hover() 模拟鼠标悬停事件
$().toggle() 模拟鼠标连续点击事件

hover()方法
// $('.box').mouseenter(function(){
//     $(this).stop().css('background','green');
// })
// $('.box').mouseleave(function(){
//     $(this).stop().css('background','red');
// })

// hover(鼠标悬停事件函数,鼠标离开事件函数) 结合了上面mouseenter 和mouseleave方法
$('.box').hover(function(){
    // 鼠标悬停
    $(this).stop().css('background','green');
},function(){
    // 鼠标离开
    $(this).stop().css('background','red');
})
toggle()方法
// 给 切换元素 绑定点击事件
$('#btn').click(function(){
    //$().toggle() 模拟了显示隐藏效果,一次点击隐藏,再次点击显示
    $('.box').toggle();
})

完整代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>合成事件</title>
    <script src="jquery-3.7.1.js"></script>
    <style>
        
    </style>
<body>

<div id="btn">切换</div>
<div class="box" style="width: 200px;height: 200px;background-color:red;"></div>



<script type="text/javascript">
// 入口函数
$(function(){
    /* 
        jquery 中有两个合成事件,hover() 事件 和 toggle()事件
        hover() 模拟鼠标悬停事件
        toggle() 模拟鼠标连续点击事件
    */ 

    // $('.box').mouseenter(function(){
    //     $(this).stop().css('background','green');
    // })
    // $('.box').mouseleave(function(){
    //     $(this).stop().css('background','red');
    // })



    // hover(鼠标悬停事件函数,鼠标离开事件函数) 结合了mouseenter 和mouseleave方法
    $('.box').hover(function(){
        // 鼠标悬停
        $(this).stop().css('background','green');
    },function(){
        // 鼠标离开
        $(this).stop().css('background','red');
    })


    // 给 切换元素 绑定点击事件
    $('#btn').click(function(){
        //$().toggle() 模拟了显示隐藏效果,一次点击隐藏,再次点击显示
        $('.box').toggle();
    })

   

})//入口函数结尾

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

动画效果

jquery中常用的动画方法:

1. ( ) . h i d e ( ) :隐藏元素 2. ().hide():隐藏元素 2. ().hide():隐藏元素2.().hide(‘slow’):慢速隐藏
3. ( ) . h i d e ( ′ n o r m a l ′ ) : 正常速度隐藏 4. ().hide('normal'):正常速度隐藏 4. ().hide(normal):正常速度隐藏4.().hide(‘normal’):快速度隐藏
5.$().hide(时间):指定隐藏时间

6. ( ) . f a d e I n ( 时间 ) : 淡入 7. ().fadeIn(时间):淡入 7. ().fadeIn(时间):淡入7.().fadeOut(时间):淡出
8.$().fadeTo(指定透明位置,透明度(0-1))

9. ( ) . s l i d e U p ( 时间 ) : 上拉 10. ().slideUp(时间):上拉 10. ().slideUp(时间):上拉10.().slideDown(时间):下拉

11. ( ) . t o g g l e ( 时间 ) : 显示和隐藏事件 12. ().toggle(时间):显示和隐藏事件 12. ().toggle(时间):显示和隐藏事件12.().fadeToggle(时间):淡入淡出显示和隐藏事件
13.$().slideToggle(时间):上拉下拉显示和隐藏事件

14.$(‘’).animate({
‘属性1’:‘属性值1’,
‘属性2’:‘属性值2’,
‘属性3’:‘属性值3’,
…},动画时间,回调函数):自定义动画 颜色需要jquery的插件配合使用 jquery-color

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>动画效果</title>
    <script src="jquery-3.7.1.js"></script>
<body>
<div id="btn">切换</div>
<div class="box" style="width: 200px;height: 200px;background-color:red;"></div>
<script type="text/javascript">
// 入口函数
$(function(){
    // 给 切换元素 绑定点击事件
    $('#btn').click(function(){
        $('.box').hide();
    })
})//入口函数结尾

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

ajax请求

ajax技术:在不重载页面的情况,与页面进行局部更新,常用的请求方式:get和post

get请求写法

// get请求
$.ajax({
    url:'', //请求地址
    method:'get', //请求方式
    success:function(res){ // 获得后端返回的数据,要做的事情
        // 当成功获取到了后端的请求后,要做的事情
    }
})

post请求写法

$.ajax({
    url:'https://www.xxx.com/',
    method:'post',
    data:{
        // 请求参数,也就是url中?后面的内容1:'值1',2:'值2'
    },
    success:function(res){
		//当成功获取到了后端的请求后,要做的事情
    }
})

代码案例

这里用 第三方接口 和风天气作为案例

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>ajax技术</title>
    <script src="jquery-3.7.1.js"></script>
<body>

<div id="weather">
    <p class='cond_txt'></p>
</div>


<script type="text/javascript">
// 入口函数
$(function(){
    /*
    ajax技术:在不重载页面的情况,与页面进行局部更新
    get post

    第三方接口 和风天气
    https://devapi.qweather.com/v7/weather/now?location=101010100&key=be57c5ee9a2c462f8bb517efd86343fc

    */   

    // get请求
    $.ajax({
        url:'https://devapi.qweather.com/v7/weather/now?location=101010100&key=be57c5ee9a2c462f8bb517efd86343fc', //请求地址
        method:'get', //请求方式
        success:function(res){ // 获得后端返回的数据,要做的事情
            // res 获取后端返回的数据 json类型数据
            var status = res.code;
            if(status === '200'){
                var cond_txt = res.now.text
                $('#weather .cond_txt').html(cond_txt);
            }
        }
    })




    /*
    post请求方式
    $.ajax({
        url:'https://devapi.qweather.com/v7/weather/now',
        method:'post',
        data:{
            location:'101010100',
            key:be57c5ee9a2c462f8bb517efd86343fc
        },
        success:function(res){

        }
    })
    */


})//入口函数结尾

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

Ajax请求案例

用ajax请求和风天气的api

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>ajax案例--实时获取天气</title>
    <style>
        * {
            padding: 0;
            margin: 0;
        }

        a {
            display: inline-block;
        }

        .header {
            width: 100%;
            height: 40px;
            line-height: 40px;
            background-color: #000;
            opacity: 0.4;
            position: relative;

        }

        .weather_now {
            display: inline-block;
        }

        .weather_now a {
            text-decoration: none;
            color: #fff;
        }

        .weather_now img {
            width: 30px;
            vertical-align: middle;
        }

        .show_weather {
            display: none;
            position: absolute;
            background-color: antiquewhite;
            top: 40px;
        }

        .everyday_item {
            display: inline-block;
            padding: 20px;
        }
    </style>
    <script src="../jquery-3.7.1.js"></script>
    <!-- 引入https://momentjs.cn/ 第三方日期格式化的库 -->
    <script src="../moment.js"></script>
</head>
<body>
<div class="header">
    <div class="weather_now">
        <a href="javascript:;">
            <span class='city'></span>
            <img src="./images/100.png" alt="" class="weatherImg">
            <span class="temp">12</span>
            <span class="cond_txt">qing</span>
            <span class="fl">33</span>
        </a>
        <div class="show_weather">
            <div class="everyday_weather">
                <div class="everyday_item">
                    <!-- <p class="everyday_title">今天(星期一)</p>
                    <img class="everyday_icon" src='./images/101.png' />
                    <p class="everyday_temp">31℃</p>
                    <p class="everyday_cond_txt">晴</p>
                    <p class="everyday_cond_wind">北风</p> -->
                </div>
                <div class="everyday_item">
                   <!--  <p class="everyday_title">今天(星期一)</p>
                    <img class="everyday_icon" src='./images/101.png' />
                    <p class="everyday_temp">31℃</p>
                    <p class="everyday_cond_txt">晴</p>
                    <p class="everyday_cond_wind">北风</p> -->
                </div>
                <div class="everyday_item">
                   <!-- <p class="everyday_title">今天(星期一)</p>
                    <img class="everyday_icon" src='./images/101.png' />
                    <p class="everyday_temp">31℃</p>
                    <p class="everyday_cond_txt">晴</p>
                    <p class="everyday_cond_wind">北风</p> -->
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    $(function () {
        // 鼠标悬浮事件
        $('.weather_now').mouseenter(function(){
            $('.show_weather').stop().fadeIn();
            getForecastWeather('https://devapi.qweather.com/v7/weather/3d?location=101010100&key=be57c5ee9a2c462f8bb517efd86343fc');
        })


        // 鼠标离开事件
        $('.weather_now').mouseleave(function(){
            $('.show_weather').stop().fadeOut();
        })


        // 轮循
        setInterval(function(){
            getForecastWeather('https://devapi.qweather.com/v7/weather/3d?location=101010100&key=be57c5ee9a2c462f8bb517efd86343fc');
            getNowWeather('https://devapi.qweather.com/v7/weather/now?location=101010100&key=be57c5ee9a2c462f8bb517efd86343fc');
        },1000*60*60)


        // 设置全局为中文
            moment.locale('zh-cn', {
                months: '一月_二月_三月_四月_五月_六月_七月_八月_九月_十月_十一月_十二月'.split('_'),
                monthsShort: '1月_2月_3月_4月_5月_6月_7月_8月_9月_10月_11月_12月'.split('_'),
                weekdays: '星期日_星期一_星期二_星期三_星期四_星期五_星期六'.split('_'),
                weekdaysShort: '周日_周一_周二_周三_周四_周五_周六'.split('_'),
                weekdaysMin: '日_一_二_三_四_五_六'.split('_'),
                longDateFormat: {
                    LT: 'HH:mm',
                    LTS: 'HH:mm:ss',
                    L: 'YYYY-MM-DD',
                    LL: 'YYYY年MM月DD日',
                    LLL: 'YYYY年MM月DD日Ah点mm分',
                    LLLL: 'YYYY年MM月DD日ddddAh点mm分',
                    l: 'YYYY-M-D',
                    ll: 'YYYY年M月D日',
                    lll: 'YYYY年M月D日 HH:mm',
                    llll: 'YYYY年M月D日dddd HH:mm'
                },
                meridiemParse: /凌晨|早上|上午|中午|下午|晚上/,
                meridiemHour: function (hour, meridiem) {
                    if (hour === 12) {
                        hour = 0;
                    }
                    if (meridiem === '凌晨' || meridiem === '早上' ||
                        meridiem === '上午') {
                        return hour;
                    } else if (meridiem === '下午' || meridiem === '晚上') {
                        return hour + 12;
                    } else {
                        // '中午'
                        return hour >= 11 ? hour : hour + 12;
                    }
                },
                meridiem: function (hour, minute, isLower) {
                    const hm = hour * 100 + minute;
                    if (hm < 600) {
                        return '凌晨';
                    } else if (hm < 900) {
                        return '早上';
                    } else if (hm < 1130) {
                        return '上午';
                    } else if (hm < 1230) {
                        return '中午';
                    } else if (hm < 1800) {
                        return '下午';
                    } else {
                        return '晚上';
                    }
                },
                calendar: {
                    sameDay: '[今天]LT',
                    nextDay: '[明天]LT',
                    nextWeek: '[下]ddddLT',
                    lastDay: '[昨天]LT',
                    lastWeek: '[上]ddddLT',
                    sameElse: 'L'
                },
                dayOfMonthOrdinalParse: /\d{1,2}(日|月|周)/,
                ordinal: function (number, period) {
                    switch (period) {
                        case 'd':
                        case 'D':
                        case 'DDD':
                            return number + '日';
                        case 'M':
                            return number + '月';
                        case 'w':
                        case 'W':
                            return number + '周';
                        default:
                            return number;
                    }
                },
                relativeTime: {
                    future: '%s内',
                    past: '%s前',
                    s: '几秒',
                    ss: '%d秒',
                    m: '1分钟',
                    mm: '%d分钟',
                    h: '1小时',
                    hh: '%d小时',
                    d: '1天',
                    dd: '%d天',
                    M: '1个月',
                    MM: '%d个月',
                    y: '1年',
                    yy: '%d年'
                },
                week: {
                    dow: 1,
                    doy: 4
                }
            })


        // 获取今天,明天,后天
            function getDay(i){
                switch (i) {
                    case 0:
                        return '今天';
                        break;
                    case 1:
                        return '明天';
                        break;
                    default:
                        return '后天';
                        break;
                }
            }


        // 获取未来三天的天气
        function getForecastWeather(url){
            // 发送ajax请求未来三天的天气
            $.ajax({
                url:url,
                method:'get',
                success:function(res){
                    console.log(res.daily);
                    var daily_forecast = res.daily;
                    // jquery中的each()方法可以用来循环遍历
                    $('.everyday_item').each(function(i){
                        // i指的是每一个div的索引
                        var cond_code_d = daily_forecast[i].iconDay;
                        var tmp_max = daily_forecast[i].tempMax;
                        var cond_txt_d = daily_forecast[i].textDay;
                        var wind_dir = daily_forecast[i].windDirDay;
                        var date = daily_forecast[i].fxDate;
                        var week = moment(date).format('dddd');
                        // 清空元素,防止元素重复
                        $(this).empty();
                        $(this).append(`
                        <p class="everyday_title">${getDay(i)}(${week})</p>
                        <img class="everyday_icon" src='./images/${100}.png' />
                        <p class="everyday_temp">${tmp_max}</p>
                        <p class="everyday_cond_txt">${cond_txt_d}</p>
                        <p class="everyday_cond_wind">${wind_dir}</p>
                        `);
                    })
                },
                error:function(err){
                    console.log(err);
                }
            })
        }


        // 获取现在天气
        function getNowWeather(url){
            // 发送ajax到和风天气服务器获取数据
            $.ajax({
                url:url,
                method:'get',
                success:function(res){
                    // 获取状态码
                    var status = res.code;
                    if(status === '200'){
                        // 城市 这里获取城市有点问题,那就先写死吧
                        var city = '北京';
                        // 实况天气图标码
                        var cond_code = res.now.icon;
                        // 天气状况
                        var cond_txt = res.now.text;
                        // 当前温度
                        var tmp = res.now.temp;
                        // 体感温度
                        var fl = res.now.feelsLike;
                        
                        // 渲染页面
                        $('.city').html(city+':');
                        $('.weatherImg').attr('src',`./images/${100}.png`);
                        $('.temp').html(tmp+'℃');
                        $('.cond_txt').html(cond_txt);
                        $('.fl').html(fl);
                    }
                },
                error:function(err){
                    // 如果请求失败,那就抛出异常
                    console.log(err);
                }
            })
        }

        // 调用自定义方法
        getNowWeather('https://devapi.qweather.com/v7/weather/now?location=101010100&key=be57c5ee9a2c462f8bb517efd86343fc');


        /*
        近三天的天气预报:
        https://devapi.qweather.com/v7/weather/3d?location=101010100&key=be57c5ee9a2c462f8bb517efd86343fc
        */

    })
</script>
</body>
</html>

localStorage本地缓存

设置值:localStorage.setItem(‘键’,JSON.stringify([{键1:值1,键2:值2,…}]))

取值:JSON.parse(localStorage.getItem(‘键’))
移除:localStorage.removeItem(‘键’)

查看本地缓存方式

  1. 打开开发者工具:
    • 在 Chrome 或 Edge 中,你可以通过按 F12 或右键点击页面元素选择“检查”来打开开发者工具。
    • 在 Firefox 中,你可以通过按 Ctrl+Shift+I(Windows/Linux)或 Cmd+Opt+I(Mac)来打开。
    • 在 Safari 中,你需要先启用“开发”菜单(在 Safari 的“偏好设置”中的“高级”标签页下勾选“在菜单栏中显示‘开发’菜单”),然后通过“开发”菜单选择“显示网页检查器”来打开。
  2. 导航到 Application 或 Storage 选项卡:
    • 在 Chrome、Firefox 和 Edge 中,开发者工具打开后,点击顶部的“Application”标签页,然后在左侧菜单中找到“Local Storage”或“Storage” > “Local Storage”部分。
    • 在 Safari 中,打开“Web 检查器”后,点击顶部的“存储”标签页,然后查看“Local Storage”部分。
  3. 查看和编辑 localStorage:
    • 在“Local Storage”部分,你将看到当前域下存储的所有 localStorage 项。你可以点击它们来查看键值对,甚至可以在这里编辑或删除它们(但请注意,这些更改将影响当前浏览器会话中的网站行为)。

jquery综合案例

tolist待办事项案例

<!DOCTYPE html>
<html>

<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
    <title>ToDoList—最简单的待办事项列表</title>
    <style>
        body {
            margin: 0;
            padding: 0;
            font-size: 16px;
            background: #CDCDCD;
        }

        header {
            height: 50px;
            background: #333;
            background: rgba(47, 47, 47, 0.98);
        }

        section {
            margin: 0 auto;
        }

        label {
            float: left;
            width: 100px;
            line-height: 50px;
            color: #DDD;
            font-size: 24px;
            cursor: pointer;
            font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
        }

        header input {
            float: right;
            width: 60%;
            height: 24px;
            margin-top: 12px;
            text-indent: 10px;
            border-radius: 5px;
            box-shadow: 0 1px 0 rgba(255, 255, 255, 0.24), 0 1px 6px rgba(0, 0, 0, 0.45) inset;
            border: none
        }

        input:focus {
            outline-width: 0
        }

        h2 {
            position: relative;
        }

        span {
            position: absolute;
            top: 2px;
            right: 5px;
            display: inline-block;
            padding: 0 5px;
            height: 20px;
            border-radius: 20px;
            background: #E6E6FA;
            line-height: 22px;
            text-align: center;
            color: #666;
            font-size: 14px;
        }

        ol,
        ul {
            padding: 0;
            list-style: none;
        }

        li input {
            position: absolute;
            top: 2px;
            left: 10px;
            width: 22px;
            height: 22px;
            cursor: pointer;
        }

        p {
            margin: 0;
        }

        li p input {
            top: 3px;
            left: 40px;
            width: 70%;
            height: 20px;
            line-height: 14px;
            text-indent: 5px;
            font-size: 14px;
        }

        li {
            height: 32px;
            line-height: 32px;
            background: #fff;
            position: relative;
            margin-bottom: 10px;
            padding: 0 45px;
            border-radius: 3px;
            border-left: 5px solid #629A9C;
            box-shadow: 0 1px 2px rgba(0, 0, 0, 0.07);
        }

        ol li {
            cursor: move;
        }

        ul li {
            border-left: 5px solid #999;
            opacity: 0.5;
        }

        li a {
            position: absolute;
            top: 2px;
            right: 5px;
            display: inline-block;
            width: 14px;
            height: 12px;
            border-radius: 14px;
            border: 6px double #FFF;
            background: #CCC;
            line-height: 14px;
            text-align: center;
            color: #FFF;
            font-weight: bold;
            font-size: 14px;
            cursor: pointer;
        }

        footer {
            color: #666;
            font-size: 14px;
            text-align: center;
        }

        footer a {
            color: #666;
            text-decoration: none;
            color: #999;
        }

        @media screen and (max-device-width: 620px) {
            section {
                width: 96%;
                padding: 0 2%;
            }
        }

        @media screen and (min-width: 620px) {
            section {
                width: 600px;
                padding: 0 10px;
            }
        }
    </style>
</head>

<body>
<header>
    <section>
        <form action="javascript:;" id="form">
            <label for="title">ToDoList</label>
            <input type="text" id="title" name="title" placeholder="添加ToDo"/>
        </form>
    </section>
</header>
<section>
    <h2>正在进行 <span id="todocount"></span></h2>
    <ol id="todolist" class="demo-box">

    </ol>
    <h2>已经完成 <span id="donecount"></span></h2>
    <ul id="donelist">

    </ul>
</section>
<footer>
    todolist.cn <a href="javascript:;">clear</a>
</footer>
<script src="jquery-3.7.1.js"></script>
</body>


<script>
$(function(){
    // 模拟数据
    var todoList = [];

    // 加载数据的方法
    function loadData(){
        var collection = localStorage.getItem('todo');
        if(collection){
            return JSON.parse(collection);
        }else{
            return [];
        }
    }


    // 保存数据的方法
    function saveData(data){
        localStorage.setItem('todo', JSON.stringify(data));
    }


    // 加载网页数据
    load();

    // 添加数据的方法
    $('#title').keydown(function(event){
        // 判断用户按下的键是否是回车键(13)
        if(event.keyCode === 13){
            // 获取输入框中的值
            var val = $(this).val();
            if(!val){
                alert('不能为空,请重新输入');
            }else{
                var data = loadData();
                data.unshift({
                    title:val,
                    done:false
                });
                // 清空input输入框中的值
                $(this).val('');
                // 保存数据
                saveData(data);
                // 更新数据
                load();
            }
        }
    })


    // 事件代理的方式 删除操作
    $('#todolist').on('click','a',function(){
        // 获取当前被点击的索引
        // index()是内置方法 每个对象都有该属性,对象的索引值
        var i = $(this).parent().index();
        // 根据索引 删除当前被点击的元素
        todoList.splice(i,1);
        // 重新加载页面
        load();
    })




    // 更新数据
    $('#todolist').on('change','input[type=checkbox]',function(){
        // 取出当前对象的index属性
        var i = parseInt($(this).attr('index'));
        update(i,'done',true);
    })
        // 更新数据
    $('#donelist').on('change','input[type=checkbox]',function(){
        // 取出当前对象的index属性
        var i = parseInt($(this).attr('index'));
        update(i,'done',false);
    })
    function update(i,key,value){
        // 从本地缓存取出数据
        var data = loadData();
        // 取出要删除的元素
        var todo = data.splice(i,1)[0];
        // 将done改为true
        todo[key] = value;
        // 替换掉原本的元素
        data.splice(i,0,todo);
        // 保存数据到本地缓存
        saveData(data);
        // 更新数据
        load();
    }


        // 编辑操作
        $('#todolist').on('click','p',function() {
        var i = parseInt($(this).attr('index'));
        var title = $(this).html();
        var $p = $(this);
        $p.html(`
            <input type="text" id='input-${i}' value=${title}>
        `)
        // 选中
        $(`#input-${i}`)[0].setSelectionRange(0, $(`#input-${i}`).val().length);
        // 获取焦点
        $(`#input-${i}`).focus();

        // 失去焦点保存更改的数据
        $(`#input-${i}`).blur(function() {
            if($(this).val().length === 0){
                $p.html(title);
                alert('内容不能为空');
            }else{
                update(i,'title',$(this).val())
            }
        })     
    })




    // 初始化加载数据
    function load(){
        var todoCount = 0;
        var doneCount = 0;
        var doneStr = '';
        var todoStr = '';
        var todoList = loadData();
        if (todoList && todoList.length > 0) {
            // 有数据
            todoList.forEach( function(data, i) {
                if(data.done){
                    // 已经完成
                    doneStr += `
                        <li>
                            <input type="checkbox" index=${i} checked='checked'>
                            <p id='p-${i}' index=${i}>${data.title}</p>
                            <a href="javascript:;">-</a>
                         </li>
                    `;
                    doneCount++;

                }else{
                    // 正在进行
                   todoStr += `
                        <li>
                            <input type="checkbox" index=${i}>
                            <p id='p-${i}' index=${i}>${data.title}</p>
                            <a href="javascript:;">-</a>
                         </li>
                    `;
                    todoCount++;
                }

                $('#todolist').html(todoStr);
                $('#donelist').html(doneStr);
                $('#todocount').html(todoCount);
                $('#donecount').html(doneCount);
            });

        }else{
            // 无数据
            $('#todolist').html('');
            $('#donelist').html('');
            $('#todocount').html(todoCount);
            $('#donecount').html(doneCount);
        }
    }
})

</script>
</html>
  • 9
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值