Python3学习之路~11.1 jQuery

jQuery API速查表: http://www.php100.com/manual/jquery/

参考:https://www.w3cschool.cn/jquery/

jQuery 简介

jQuery是一个JavaScript函数库。

jQuery是一个轻量级的"写的少,做的多"的JavaScript库。

jQuery 库可以通过一行简单的标记被添加到网页中。

jQuery库包含以下功能:

  • HTML 元素选取
  • HTML 元素操作
  • CSS 操作
  • HTML 事件函数
  • JavaScript 特效和动画
  • HTML DOM 遍历和修改
  • AJAX
  • Utilities

提示: 除此之外,Jquery还提供了大量的插件。

 

二 jQuery 安装

可以通过多种方法在网页中添加 jQuery。 您可以使用以下方法:

  • 从 jquery.com 下载 jQuery 库
  • 从 CDN 中载入 jQuery, 如从 Google 中加载 jQuery

 

三 jQuery 语法

jQuery 语法是通过选取 HTML 元素,并对选取的元素执行某些操作。

基础语法: $(selector).action()

  • 美元符号定义 jQuery
  • 选择符(selector)"查询"和"查找" HTML 元素
  • jQuery 的 action() 执行对元素的操作

实例:

$(this).hide() - 隐藏当前元素

$("p").hide() - 隐藏所有段落

$("p .test").hide() - 隐藏所有 class="test" 的段落

$("#test").hide() - 隐藏所有 id="test" 的元素

文档就绪事件

所有 jQuery 函数位于一个 document ready 函数中:

 $(document).ready(function(){

   // 开始写 jQuery 代码...

 }); 

这是为了防止文档在完全加载(就绪)之前运行 jQuery 代码。

如果在文档没有完全加载之前就运行函数,操作可能失败。下面是两个具体的例子:

  • 试图隐藏一个不存在的元素
  • 获得未完全加载的图像的大小

提示:简洁写法(与以上写法效果相同):

$(function(){

   // 开始写 jQuery 代码...

 }); 

以上两种方式你可以选择你喜欢的方式实现文档就绪后执行jQuery方法。

 

四 jQuery 选择器

1.元素选择器

jQuery 元素选择器基于元素名选取元素。

在页面中选取所有 <p> 元素:

$("p")

实例  用户点击按钮后,所有 <p> 元素都隐藏:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>jQuery元素选择器</title>
    <script src="jquery-3.4.1.js"></script>
    <script>
        $(document).ready(function () {
            $("button").click(function () {
                $("p").hide();
            });
        });
    </script>
</head>
<body>
<h2>这是一个标题</h2>
<p>这是一个段落。</p>
<p>这是另一个段落。</p>
<button>点我</button>
</body>
</html>
View Code

2.#id 选择器

jQuery #id 选择器通过 HTML 元素的 id 属性选取指定的元素。

页面中元素的 id 应该是唯一的,所以您要在页面中选取唯一的元素需要通过 #id 选择器。

通过 id 选取元素语法如下:

$("#test")

实例  当用户点击按钮后,有 id="test" 属性的元素将被隐藏:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>#id选择器</title>
    <script src="jquery-3.4.1.js"></script>
    <script>
        $(document).ready(function () {
            $("button").click(function () {
                $("#test").hide();
            });
        });
    </script>
</head>
<body>
<h2>这是一个标题</h2>
<p>这是一个段落。</p>
<p id="test">这是另一个段落。</p>
<button>点我</button>
</body>
</html>
View Code

3 .class 选择器

jQuery 类选择器可以通过指定的 class 查找元素。

语法如下:

$(".test")

实例  用户点击按钮后所有带有 class="test" 属性的元素都隐藏:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>.class选择器</title>
    <script src="jquery-3.4.1.js"></script>
    <script>
        $(document).ready(function () {
            $("button").click(function () {
                $(".test").hide();
            });
        });
    </script>
</head>
<body>
<h2 class="test">这是一个标题</h2>
<p class="test">这是一个段落。</p>
<p>这是另一个段落。</p>
<button>点我</button>
</body>
</html>
View Code

4.其它

语法                       描述 
$("*")                    选取所有元素     
$(this)                   选取当前 HTML 元素   
$("p.intro")              选取 class 为 intro 的 <p> 元素    
$("div,span,p.myClass")   选取所有的<div>元素、<span>元素、class为myClass的<p>元素 

层级
$("form input")           找到表单中所有的 input 元素
$("form > input")         匹配表单中所有的子级input元素
$("label + input")        匹配所有跟在 label 后面的 input 元素
$("form ~ input")         找到所有与表单同辈的 input 元素

基本筛选器
$("p:first")              选取第一个 <p> 元素  
$("ul li:first")          选取第一个 <ul> 元素的第一个 <li> 元素
$("input:not(:checked)")  查找所有未选中的 input 元素
$("tr:even")              选取偶数位置的 <tr> 元素(查找表格的1、3、5...行(即索引值0、2、4...)) 
$("tr:odd")               选取奇数位置的 <tr> 元素(查找表格的2、4、6行(即索引值1、3、5...))
$("tr:eq(1)")             匹配一个给定索引值(从 0 开始计数)的元素,即查找第2个 <tr> 元素
$("tr:gt(0)")             匹配所有大于给定索引值的 <tr> 元素
$("p:lang(it)")           选择指定语言的所有元素
$('li:last')              匹配的后一个<li>元素
$("tr:lt(2)")             匹配所有小于给定索引值2的 <tr> 元素
$(":header")              匹配如 h1, h2, h3之类的标题元素
$("div:not(:animated)").animate({ left: "+=20" }, 1000); 对不在执行动画效果的元素执行一个动画特效

内容
$("div:contains('John')") 查找所有包含 "John" 的 <div> 元素
$("td:empty")             查找所有不包含子元素或者文本的空<td>元素
$("div:has(p)")           查找所有的包含 <p> 元素的 <div> 元素
$("td:parent")            查找所有含有子元素或者文本的 <td> 元素

属性
$("[href]")               选取带有 href 属性的元素    
$("div[id]")              查找所有含有 id 属性的 <div> 元素
$("a[target='_blank']")   选取所有 target 属性值等于 "_blank" 的 <a> 元素  
$("a[target!='_blank']")  选取所有 target 属性值不等于 "_blank" 的 <a> 元素  
$("input[name^='news']")  查找所有 name 以 'news' 开始的 <input> 元素
$("input[name$='letter']")   查找所有 name 以 'letter' 结尾的 <input> 元素
$("input[name*='man']")      查找所有 name 包含 'man' 的 <input> 元素
$("input[id][name$='man']")  找到所有含有 id 属性,并且它的 name 属性是以 man 结尾的 <input> 元素

子元素
$("ul li:first-child")    选取每个 <ul> 元素中的第一个 <li> 元素  
$("ul li:last-child")     选取每个 <ul> 元素中的最后一个 <li> 元素 
$("ul li:nth-child(2)")   选取每个 <ul> 元素中的第2个 <li> 元素(注意nth-child从1开始)

表单
$(":input")               查找所有的 <input> 元素
$(":text")                查找所有文本框[ <input type="text" /> ]
$(":password")            查找所有密码框[ <input type="password" /> ]
$(":radio")               查找所有单选按钮[ <input type="radio" /> ]
$(":checkbox")            查找所有复选框[ <input type="checkbox" /> ]
$(":submit")              查找所有提交按钮[ <input type="submit" /> ]
$(":image")               查找所有图像域[ <input type="image" /> ]
$(":reset")               查找所有重置按钮[ <input type="reset" /> ]
$(":button")              查找所有按钮[ <input type="button" />,<button></button> ] 
$(":file")                查找所有文件域[ <input type="file" /> ]

更多:http://www.php100.com/manual/jquery/

 

五 属性

属性
$("img").attr("src");                                  返回文档中所有图像的src属性值
$("img").attr({ src: "test.jpg", alt: "Test Image" }); 为所有图像设置src和alt属性
$("img").attr("src","test.jpg");                       为所有图像设置src属性
$("img").attr("title", function() { return this.src });把src属性的值设置为title属性的值
$("img").removeAttr("src");                            将图像的src属性删除
$("input[type='checkbox']").prop("checked");           返回复选框checked属性的值,选中为true,没选中为false
$("input[type='checkbox']").prop({disabled: true});    禁用页面上的所有复选框
$("input[type='checkbox']").prop("disabled", false);   禁用所有页面上的复选框
$("input[type='checkbox']").prop("checked", true);     选中所有页面上的复选框
$("input[type='checkbox']").prop("checked", function( i, val ) {return !val;}); 通过函数来设置所有页面上的复选框被选中

CSS类
$("p").addClass("selected");              为匹配的元素加上 'selected' 类
$("p").addClass("selected1 selected2");   为匹配的元素加上 'selected1' 和 'selected2'类
$("p").removeClass("selected");           从匹配的元素中删除 'selected' 类
$("p").removeClass();                     删除匹配元素的所有类
$("p").toggleClass("selected");           为匹配的元素切换 'selected' 类(如果存在(不存在)就删除(添加)一个类)

HTML代码/文本/值
$('p').html();                      返回p元素的内容
$("p").html("Hello <b>world</b>!"); 设置所有 p 元素的内容
$('p').text();                      返回p元素的文本内容
$("p").text("Hello world!");        设置所有 p 元素的文本内容
$("input").val();                   获取文本框中的值
$("input").val("hello world!");     设定文本框的值

  

六 CSS

CSS
$("p").css("color");                                      取得第一个段落的color样式属性的值
$("p").css({ "color": "#ff0011", "background": "blue" }); 将所有段落的字体颜色设为红色并且背景为蓝色。
$("p").css("color","red");                                将所有段落字体设为红色
$("p").css("background-color","red");                     把所有 p 元素的背景颜色更改为红色

位置
$("p").offset();        获取匹配元素在当前视口的相对偏移
$("p").position();      获取匹配元素相对父元素的偏移
$("p").scrollTop();     获取匹配元素相对滚动条顶部的偏移

offset VS position:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>位置</title>
    <script src="jquery-3.4.1.js"></script>
    <script>
        $(function () {
            $("#offset").click(function () {
                var result1 = $("#content").offset();
                console.log(result1)
            });
             $("#position").click(function () {
                var result2 = $("#content").position();
                console.log(result2)
            });
        });
    </script>
</head>
<body>
<div style="float: left;width: 100px;margin: 20px;border: 1px solid red">
    <div style="margin: 10px;padding: 20px" id="content">content</div>
</div>

<button id="offset">offset</button>
<button id="position">position</button>

<p>这里offset和position相差10px,是由于margin: 10px造成的。margin: 10px不属于content,而padding: 20px属于content。</p>
<p>offset():获取匹配元素在当前视口的相对偏移。</p>
<p>position():获取匹配元素相对父元素的偏移。</p>
</body>
</html>
View Code

scrollTop实现返回顶部功能:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>返回顶部</title>
    <style>
        .hide{
            display: none;
        }
    </style>
    <script src="jquery-3.4.1.js"></script>
    <script>
        $(function(){
            //下拉框距离顶部大于50px时,出现“返回顶部”,否则“返回顶部”隐藏。
            $(window).scroll(function () {
                var top = $(this).scrollTop();
                if(top>50){
                    $('#gotop').removeClass('hide');
                }else{
                    $('#gotop').addClass('hide');
                }
            });

            //返回顶部
            $('#gotop').click(function () {
                $(window).scrollTop(0);
            });
        })
    </script>
</head>
<body>
    <!--
有些网站的返回顶部功能使用的是锚,我们也可以用scrollTop实现此功能。
position: fixed 实现将某个东西放在界面右下角
cursor:pointer 实现鼠标变小手
    -->
    <p>这是顶部</p>
    <div id='gotop' class='hide' style="position:fixed;right:30px;bottom:30px;cursor:pointer;">返回顶部</div>
    <div style="height: 900px;"></div>
</body>
</html>
View Code

 

七 文档处理

内部插入
$("p").append("<b>Hello</b>");  向所有段落中追加一些HTML标记
$("p").appendTo("div");         把所有段落追加到div元素中
$("p").prepend("<b>Hello</b>"); 向所有段落中前置一些HTML标记代码
$("p").prependTo("#foo");       把所有匹配的元素前置到另一个、指定的元素元素集合中 

删除
$("p").empty();                 把所有段落的子元素(包括文本节点)删除

  

八 筛选

过滤
$("p").eq(1)                   获取匹配的第二个元素,与$("p:eq(1)")相同
$('li').first()                获取匹配的第一个元素
$('li').last()                 获取匹配的最后个元素
$("div").hasClass("protected") 获取包含protected类的div元素

查找
$("div").children()            查找DIV中的每个子元素
$("div").children(".selected") 在每个div中查找包含protected类的元素
$("p").find("span")            从所有的段落开始,进一步搜索下面的span元素。与$("p span")相同
$("p").next()                  找到每个段落的后面紧邻的同辈元素
$("p").next(".selected")       找到每个段落的后面紧邻的同辈元素中类名为selected的元素
$("p").parent()                查找每个段落的父元素
$("p").parent(".selected")     查找段落的父元素中每个类名为selected的父元素
$("div").siblings()            找到每个div的所有同辈元素
$("div").siblings(".selected") 找到每个div的所有同辈元素中带有类名为selected的元素

children&parent&next&siblings等查找实例:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>查找</title>
    <script src="jquery-3.4.1.js"></script>
    <style>
        .hide{
            display: none;
        }
    </style>
    <script>
        $(function () {
            $(".title").click(function () {
                $(this).parent().siblings().children(".body").addClass("hide");
                $(this).next().removeClass("hide");
            })
        })
    </script>
</head>
<body>
    <div class="container">
        <div>
            <div class="title">Menu1</div>
            <div class="body hide">
                <a href="">content1</a>
                <a href="">content2</a>
                <a href="">content3</a>
            </div>
        </div>
        <div>
            <div class="title">Menu2</div>
            <div class="body hide">
                <a href="">content1</a>
                <a href="">content2</a>
                <a href="">content3</a>
            </div>
        </div>
        <div>
            <div class="title">Menu3</div>
            <div class="body hide">
                <a href="">content1</a>
                <a href="">content2</a>
                <a href="">content3</a>
            </div>
        </div>
        <div>
            <div class="title">Menu4</div>
            <div class="body hide">
                <a href="">content1</a>
                <a href="">content2</a>
                <a href="">content3</a>
            </div>
        </div>
        <div>
            <div class="title">Menu5</div>
            <div class="body hide">
                <a href="">content1</a>
                <a href="">content2</a>
                <a href="">content3</a>
            </div>
        </div>
    </div>
</body>
</html>
View Code

 

九 事件

两种jQuery事件扩展方式:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title></title>
    <script src="jquery-3.4.1.js"></script>
    <script src="myextendjquery.js"></script>
    <script>
        $(document).ready(function () {
            $("#all").click(function () {
                $("#body").allcheck();
            });
            $("#unall").click(function () {
                $("#body").uncheck();
            });
            $("#all2").click(function () {
                $.jallcheck("#body");
            });
            $("#unall2").click(function () {
                $.unjallcheck("#body");
            });
        });
    </script>
</head>
<body>
    <div id="each">
        <div>
            <input id="all" type="button" value="全选"/>
            <input id="unall" type="button"  value="取消"/>
            <input id="all2" type="button" value="全选2"/>
            <input id="unall2" type="button" value="取消2"/>
        </div>
    </div>
    <table id="body">
        <tr>
            <td><input name="nid" type="checkbox" /> </td>
            <td></td>
        </tr>
        <tr>
            <td><input name="nid" type="checkbox" /> </td>
            <td></td>
        </tr>
        <tr>
            <td><input name="nid" type="checkbox" /> </td>
            <td></td>
        </tr>
        <tr>
            <td><input name="nid" type="checkbox" /> </td>
            <td></td>
        </tr>
        <tr>
            <td><input name="nid" type="checkbox" /> </td>
            <td></td>
        </tr>
    </table>
</body>
</html>
test.html
(function () {
    jQuery.fn.extend({
        allcheck:function () {
            $(this).find(":checkbox").each(function () {
                this.checked = true;
            });
        },
        uncheck:function () {
            $(this).find(":checkbox").each(function () {
                this.checked = false;
            });
        }
    });
    //jQuery新版本貌似不太支持这种方式,有bug,只能点击一次,点击第二次就失效了。
    jQuery.extend({
        jallcheck:function (arg) {
            $(arg).find(":checkbox").attr("checked",true);
        },
        unjallcheck:function (arg) {
            $(arg).find(":checkbox").attr("checked",false);
        }
    });
})();
myextendjquery.js

 

十 模态对话框

实例

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>jQuery模态对话框</title>
    <script src="jquery-3.4.1.js"></script>
    <style>
        .cover{
           position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background-color: #b0b0b0;
            opacity: 0.4;
            z-index: 2;
        }
        .hide{
            display:none;
        }
        .modal{
            position: fixed;
            left: 50%;
            top: 40%;
            width: 500px;
            height: 400px;
            background-color: white;
            margin-left: -250px;
            margin-top: -200px;
            z-index: 3;
        }
    </style>
</head>
<body>
    <div class="cover hide"></div>

    <div class="modal hide">
        <div>
            <label for="name">姓名</label><input type="text" id ="name"/>
        </div>
        <div>
            <label for="hobby">爱好</label><input type="text" id ="hobby"/>
        </div>
        <button id="submit">提交</button>
        <button id="cancel">取消</button>
    </div>

    <button id="add">新增</button>

    <table border="1">
        <thead>
        <tr>
            <td>#</td>
            <td>姓名</td>
            <td>爱好</td>
            <td colspan="2" style="text-align: center">操作</td>
        </tr>
        </thead>
        <tbody>
        <tr>
            <td><input type="checkbox" /></td>
            <td>name1</td>
            <td>hobby1</td>
            <td><button class="delete">删除</button></td>
            <td><button class="edit">编辑</button> </td>
        </tr>
        <tr>
            <td><input type="checkbox" /></td>
            <td>name2</td>
            <td>hobby2</td>
            <td><button class="delete">删除</button></td>
            <td><button class="edit">编辑</button> </td>
        </tr>
        <tr>
            <td><input type="checkbox" /></td>
            <td>name3</td>
            <td>hobby3</td>
            <td><button class="delete">删除</button></td>
            <td><button class="edit">编辑</button> </td>
        </tr>
        </tbody>
    </table>
    <script>
        $(document).ready(function () {
            //新增按钮
            $("#add").click(function () {
                $("#name,#hobby").prop("value","");
                $(".cover,.modal").removeClass("hide");
            });

            //删除按钮,用到事件委托,主要是因为新增的行不会自动添加按钮事件
            $("tbody").on("click",".delete",function () {
                $(this).parent().parent().remove();
            });

            //编辑按钮
            $("tbody").on("click",".edit",function () {
                //设定一个标志位
                $("#submit").data("flag",$(this));
                var name = $(this).parent().prev().prev().prev().text();
                var hobby = $(this).parent().prev().prev().text();
                $("#name").val(name);
                $("#hobby").val(hobby);
                $(".cover,.modal").removeClass("hide");

            })

            //提交按钮
            $("#submit").click(function () {

                var name = $("#name").val();
                var hobby = $("#hobby").val();

                //标志位
                var flag = $("#submit").data("flag")

                if(flag == undefined){
                    var newline = "        <tr>" +
                        "            <td><input type=\"checkbox\" /></td>" +
                        "            <td>" + name + "</td>" +
                        "            <td>" + hobby + "</td>" +
                        "            <td><button class=\"delete\">删除</button></td>" +
                        "            <td><button class=\"edit\">编辑</button> </td>"+
                        "        <tr>";
                    console.log(newline)

                    $("tbody").append(newline);
                }else{
                    flag.parent().prev().prev().prev().text(name);
                    flag.parent().prev().prev().text(hobby);
                }

                //清空标志位
                $("#submit").removeData("flag");

                $(".cover,.modal").addClass("hide");

            });

            //取消按钮
            $("#cancel").click(function () {
                $(".cover,.modal").addClass("hide");
            });
        });
    </script>

</body>
</html>
View Code

 

十一 ajax

Ajex可实现跨域请求,所谓跨域请求,就是我的网站请求别的网站的一些数据,比如说调用天气接口获得气象局的天气信息。

普通的请求和跨域的请求有3点不同:

1.URL不同,本地请求可以只填写路径,而跨域请求必须有完整域名或者服务器IP;
2.dataType不同,跨域请求的dataType值必须为'jsonp';
3.callback不同,跨域请求时,本站和远程站点必须定义相同的callback,类似于一个key或者函数,以实现互通(因为远程站点不会随随便便让你来调用它的数据,二者必须约定一些东西才可以),而本地请求不需要。

实例

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>ajex</title>
    <script src="jquery-3.4.1.js"></script>
    <script>
        $(document).ready(function () {
            $("button").click(function () {
                AjaxRequestTemote();
            });

            //跨域请求(访问其他站的数据)
            function AjaxRequestRemote() {
                $.ajax({
                    type:'POST',
                    url:'http://127.0.0.1:80',//其他站的URL
                    catch:false,
                    async:true,
                    dataType:'jsonp',//定义了jsonp说明这个是跨域请求
                    jsonpCallback:"callback",//类似于key,只有远程server和本地都有callback时,跨域请求才能成功
                    success:function (data) {
                        $('.container').append(data.name);
                    }
                });
             }

            function callback(arg) {
                return arg;
            }

            //普通请求(不跨域)
            function AjaxRequest() {
                $.ajax({
                    type:'POST',
                    url:'/home/index.html',
                    catch:false,
                    async:true,
                    dataType:'json',
                    success:function (data) {
                        $('.container').append(data.name);
                    }
                });
            }

        });
    </script>
</head>
<body>
<button>点我</button>
<div class="container"></div>
</body>
</html>

<!--
#服务器端对应代码
#! /usr/bin/env python
def RunServer(environ,start_response):
    #其他站
    start_response('200 ok',[('Content-Type','application/json')])
    data='callback'+"({name:'xiaoming',age:18})"
    return data
    #本站
    #start_response('200 ok',[('Content-Type','application/json')])
    #data={name:'xiaoming',age:18}
    #return data

-->
View Code

 

posted @ 2024-07-02 19:33  zhengna  阅读(6)  评论(0编辑  收藏  举报