zoukankan      html  css  js  c++  java
  • jQuery学习笔记

    一、jQuery基本知识

    学习jQuery之前需要掌握的基础知识:

    • HTML
    • CSS
    • JavaScript

    1.1、What is jQuery?

    jQuery是一个JavaScript函数库。

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

    jQuery库包含以下功能:

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

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

    1.2、为什么使用 jQuery ?

    目前网络上有大量开源的 JS 框架, 但是 jQuery 是目前最流行的 JS 框架,而且提供了大量的扩展。

    很多大公司都在使用 jQuery, 例如:

    • Google
    • Microsoft
    • IBM
    • Netflix

    1.3、jQuery与DOM编程的区别

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
        <div id="i1">Hello,jQuery.</div>
    
        <script src="../jquery-1.12.4.js"></script>
        <script>
            //DOM编程方式
            // document.getElementById('i1').onclick = function(){
            //     alert("For DOM");
            // };
    
            //jQuery编程方式
            $('#i1').click(function(){
                alert("For jQuery");
            });
        </script>
    </body>
    </html>
    DOM&jQuery

    1.4、版本与浏览器兼容问题

    • 1.x 1.12 兼容性较好支持低版本IE
    • 2.x 对低版本的IE兼容性不太好
    • 3.x

    1.5、jQuery与DOM对象转换

    jquery对象[0] => Dom对象

    Dom对象 => $(Dom对象)

    jQuery学习网站:http://jquery.cuishifeng.cn/

    二、jQuery选择器

    2.1、id选择器

    $('#id')

    2.2、class选择器

    <div class='c1'></div>
    $(".c1")

    2.3、标签选择器

    <div id='i10' class='c1'>
        <a>a</a>
        <a>b</a>
    </div>
    <div class='c1'>
        <a>c</a>
    </div>
    <div class='c1'>
        <div class='c2'></div>
    </div>
    <script src="../jquery-1.12.4.js"></script>
    <script>
        $("a").css("background-color","red");
    </script>

    2.4、组合选择器

    <div id='i10' class='c1'>
        <a>f</a>
        <a>f</a>
    </div>
    <div class='c1'>
        <a>f</a>
    </div>
    <div class='c1'>
        <div class='c2'> </div>
    </div>
    <script src="../jquery-1.12.4.js"></script>
    <script>
        $('a').css("color","red");
        $('.c2');
    
        $('a,.c2,#i10').css("background-color","black");    //拿到所有a标签,.c2标签,id为i10的标签
    </script>

    2.5、层级选择器

    $('#i10 a') 子子孙孙    // 获取id为i10标签下的所有a标签
    $('#i10>a') 儿子

    2.6、基本筛选器

    :first

    :last

    :eq()

    2.7、属性

    $('[alex]')       获取具有alex属性的所有标签
    $('[alex="123"]') 获取alex属性等于123的标签
    
    
    <input type='text'/>
    <input type='text'/>
    <input type='file'/>
    <input type='password'/>
    
    $("input[type='text']")        获取type属性为text的input标签
    $(':text')        获取属性为text的所有input标签

    2.8、实例一

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
        <div id="i1">
            <input type="button" value="全选" onclick="CheckAll()"/>
            <input type="button" value="取消" onclick="CancleAll()"/>
            <input type="button" value="复选" onclick="ReverseAll()"/>
        </div>
    
        <table border="1">
            <thead>
                <th>选项</th>
                <th>IP</th>
                <th>PORT</th>
            </thead>
            <tbody id="tb">
                <tr>
                    <td><input type="checkbox"/></td>
                    <td>192.168.1.1</td>
                    <td>80</td>
    
                </tr>
    
                <tr>
                    <td><input type="checkbox"/></td>
                    <td>192.168.1.2</td>
                    <td>80</td>
    
                </tr>
    
                <tr>
                    <td><input type="checkbox"/></td>
                    <td>192.168.1.3</td>
                    <td>80</td>
    
                </tr>
            </tbody>
        </table>
        <script src="../jquery-1.12.4.js"></script>
        <script>
            function CheckAll(){
                $("#tb :checkbox").prop("checked", true);
            }
    
            function CancleAll(){
                $("#tb :checkbox").prop("checked",false);
            }
    
            function ReverseAll() {
                $("#tb :checkbox").each(function () {
                    // if ($(this).prop('checked')) {
                    //     $(this).prop('checked', false);
                    // } else {
                    //     $(this).prop('checked', true);
                    // }
                    var v = $(this).prop("checked")?false:true;
                    $(this).prop("checked", v);
                });
    
            }
    
        </script>
    </body>
    </html>
    多选框

    2.9、实例二

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
        <style>
            .header{
                background-color: black;
                color: wheat;
            }
            .content{
                min-height: 50px;
            }
            .hide{
                display: none;
            }
        </style>
    </head>
    <body>
        <div style="height: 400px; 200px;border: 1px solid #dddddd">
            <div class="item">
                <div class="header">标题一</div>
                <div id="i1" class="content hide">内容</div>
            </div>
    
            <div class="item">
                <div class="header">标题二</div>
                <div class="content hide">内容</div>
            </div>
    
            <div class="item">
                <div class="header">标题三</div>
                <div class="content hide">内容</div>
            </div>
        </div>
        <script src="../jquery-1.12.4.js"></script>
        <script>
            $('.header').click(function(){ //给所有的.header标签绑定onclick事件
                // 当前点击的标签 $(this)
                // 获取某个标签的下一个标签
                // 获取某个标签的父标签
                // 获取所有的兄弟标签
                // 添加样式和移除样式
                // $('.i1').addClass('hide')
                // $('#i1').removeClass('hide')
                // var v = $("this + div");
                // $("label + input")
                // console.log(v);
                //
                // $("afsldkfja;skjdf;aksdjf")
    
                // 筛选器
                /*
                $(this).next()      下一个
                $(this).prev()      上一个
                $(this).parent()    父
                $(this).children()  孩子
                $('#i1').siblings() 兄弟
                $('#i1').find('#i1') 子子孙孙中查找
                // . . .
                //
                $('#i1').addClass(..)
                $('#i1').removeClass(..)
                */
    
                // 链式编程
                // $(...).click(function(){
                //     this..
                // })
    
    
    //            $(this).next().removeClass('hide');
    //            $(this).parent().siblings().find('.content').addClass('hide')
                $(this).next().removeClass('hide').parent().siblings().find('.content').addClass('hide');
            })
        </script>
    </body>
    </html>
    菜单

    三、jQuery筛选器

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
        <p id="p1">a</p>
        <p>b</p>
        <p>c</p>
        <div>
            <a>abc</a>
        </div>
        <div>123</div>
        <script src="../jquery-1.12.4.js"></script>
        <script>
            var test = $("#p1").next();     //获取id为p1的标签的下一个元素
            console.log(test[0]);
        </script>
    </body>
    </html>
    next

    结果:

    var test = $("#p1").nextAll();  //获取id为p1的标签后面所有标签
    nextAll
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
        <p id="p1">a</p>
        <p>b</p>
        <p>c</p>
        <div>
            <a>abc</a>
        </div>
        <div id="i1">123</div>
        <script src="../jquery-1.12.4.js"></script>
        <script>
            // var test = $("#p1").next();     //获取id为p1的标签的下一个元素
            //var test = $("#p1").nextAll();  //获取id为p1的标签后面所有标签
            $("#p1").nextUntil("#i1").css("color", "green"); //给#p1后面直到#i1前的元素加上绿色的字体颜色
        </script>
    </body>
    </html>
    nextUntil

    结果:

    常用筛选器方法

    $('#i1').prev()                      获取#i1前面的一个元素
    $('#i1').prevAll()                  获取#i1前面的所有元素
    $('#i1').prevUntil('#ii1')        获取#i1前面到#ii1的所有元素
    
    
    $('#i1').parent()                  查找父标签
    $('#i1').parents()                 查找祖先标签
    $('#i1').parentsUntil()           查找#i1的祖先,但不包括某个标签
    
    $('#i1').children()                查找孩子标签
    $('#i1').siblings()                 查找除自己以外的兄弟标签
    $('#i1').find()                      查找#i1标签下面的某个标签
    $('li:eq(1)')                          获取一个给定索引值的元素
    $('li').eq(1)
    $('li')first()                         获取li标签的第一个元素
    $('li')last()                          获取li标签的最后一个元素
    hasClass(class)                    检查当前的元素是否含有某个特定的类,如果有,则返回true。

    四、jQuery文本操作

    $(..).text()           # 获取文本内容
    $(..).text(“<a>1</a>”) # 设置文本内容
    
    $(..).html()
    $(..).html("<a>1</a>")
    
    $(..).val()        #获取标签的value值,括号内填参数表示设置value值
    $(..).val(..)

    4.1、实例一

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
        <style>
            .hide{
                display: none;
            }
            .model{
                background-color: #dddddd;
                position: fixed;
                top: 50%;
                right: 50%;
                width: 500px;
                height: 400px;
                margin-top: -200px;
                margin-right: -250px;
                border: 1px solid black;
                z-index: 10;
            }
            .shadow{
                position: fixed;
                top: 0;
                right: 0;
                bottom: 0;
                left: 0;
                opacity: 0.6;
                background-color: black;
                z-index: 9;
            }
        </style>
    </head>
    <body style="background-color: #dddddd;">
        <div>
            <input type="button" value="添加" onclick="AddElement()"/>
            <input type="button" value="全选" onclick="ChooseAll()"/>
            <input type="button" value="取消" onclick="CancelAll()"/>
            <input type="button" value="反选" onclick="ReverseAll()"/>
        </div>
        <table border="1" id="tb" style="text-align: center">
            <tr>
                <td>选项</td>
                <td>IP</td>
                <td>Port</td>
                <td>Status</td>
                <td>编辑</td>
                <td>删除</td>
            </tr>
    
            <tr>
                <td id="box"><input type="checkbox"/></td>
                <td target="ip_address">192.168.1.100</td>
                <td target="port">22</td>
                <td target="status">True</td>
                <td class="edit">Edit</td>
                <td class="del">Delete</td>
            </tr>
    
            <tr>
                <td id="box"><input type="checkbox"/></td>
                <td target="ip_address">192.168.1.101</td>
                <td target="port">22</td>
                <td target="status">True</td>
                <td class="edit">Edit</td>
                <td class="del">Delete</td>
            </tr>
    
            <tr>
                <td id="box"><input type="checkbox"/></td>
                <td target="ip_address">192.168.1.102</td>
                <td target="port">22</td>
                <td target="status">True</td>
                <td class="edit">Edit</td>
                <td class="del">Delete</td>
            </tr>
    
            <tr>
                <td id="box"><input type="checkbox"/></td>
                <td target="ip_address">192.168.1.103</td>
                <td target="port">22</td>
                <td target="status">True</td>
                <td class="edit">Edit</td>
                <td class="del">Delete</td>
            </tr>
        </table>
    
        <div class="model hide">
            <input type="text" name="ip_address"/>
            <input type="text" name="port"/>
            <input type="text" name="status"/>
            <div>
                <input type="button" value="确定" onclick="ConfirmModel()"/>
                <input type="button" value="返回" onclick="BackModel()"/>
            </div>
        </div>
    
        <div class="shadow hide"></div>
    
        <script src="../jquery-1.12.4.js"></script>
        <script>
            function AddElement(){
                //增加元素,显示对话框功能
                $(".model").removeClass('hide');
            }
            function BackModel(){
                //返回,隐藏对话框功能
                $('.model, .shadow').addClass('hide');
                $('.model input[type="text"]').val("")
            }
            function ChooseAll(){
                //全选功能
                $('#tb :checkbox').prop("checked", true);
            }
            function CancelAll(){
                //取消全选功能
                $('#tb :checkbox').prop("checked", false);
            }
            function ReverseAll(){
                //反选功能
                $('#tb :checkbox').each(function(){     //循环元素
                    var v = $(this).prop('checked')?false:true;     //三元运算,如果checked为true,则v等于false,否则等于true.
                    $(this).prop('checked', v);
                })
            }
            function ConfirmModel(){
                //确认添加 功能
                var tr = document.createElement('tr');  //创建一个tr标签
                var td1 = document.createElement('td'); //创建一个td标签
                td1.innerText = $(".model input[name='ip_address']").val();
                var td2 = document.createElement('td'); //创建一个td标签
                td2.innerText = $(".model input[name='port']").val();
                var td3 = document.createElement('td'); //创建一个td标签
                td3.innerText = $(".model input[name=status]").val();
                var td4 = document.createElement('td');
                $(td4).addClass('edit');
                $(td4).text("Edit");
                var td5 = document.createElement('td');
                $(td5).addClass('del');
                $(td5).text("Delete");
                var td6 = document.createElement('td');
                $(td6).html("<input type="checkbox"/>");
    
                $(tr).append(td6);
                $(tr).append(td1);
                $(tr).append(td2);
                $(tr).append(td3);
                $(tr).append(td4);
                $(tr).append(td5);
                $('#tb').append(tr);
                $(".model, .shadow").addClass('hide');
            }
            $('.del').click(function(){
                //删除功能
                $(this).parent().remove();
            });
    
            $('.edit').click(function(){
                //编辑功能(功能不完善,无法编辑后保存)
                $('.model,.shadow').removeClass('hide');
                //获取input中的内容替换td中的内容
                var tds = $(this).prevUntil('#box');
                console.log(tds[0]);
                console.log(tds[1]);
                console.log(tds[2]);
                console.log(tds[3]);
                tds.each(function(){
                    //获取td的name属性值
                    var n = $(this).attr('target');
                    console.log(n);
                    //获取td中的内容
                    var text = $(this).text();
                    console.log(text);
                    var a1 = '.model input[name="';
                    var a2 = '"]';
                    var temp = a1 + n + a2;
                    console.log(temp);
                    $(temp).val(text);
                });
            });
        </script>
    </body>
    </html>
    编辑框

    五、jQuery样式操作

    addClass    增加class属性。
    removeClass  删除class属性。
    toggleClass  如果存在(不存在)就删除(添加)一个class属性。

    5.1、实例一

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
        <style>
            .hide{
                display: none;
            }
            .cursor{
                cursor: progress;
            }
        </style>
    </head>
    <body>
        <input id="i1" type="button" class="cursor" value="开关"/>
    
        <div id="i2" class="hide" style='color: red;'>hello</div>
        <script src="../jquery-1.12.4.js"></script>
        <script>
            $("#i1").click(function(){
                if($('#i2').hasClass('hide')){
                    $('#i2').removeClass('hide');
                }else{
                    $('#i2').addClass('hide');
                }
            })
        </script>
    </body>
    </html>
    开关

    六、jQuery属性操作

    # attr专门用于做自定义属性
    $(..).attr('n')
    $(..).attr('n','v')
    $(..).removeAttr('n')
    
    <input type='checkbox' id='i1'  />
    
    
    # prop专门用于chekbox,radio
    $(..).prop('checked')        #获取值
    $(..).prop('checked', true)        #设置值
    
    index 获取索引位置

    6.1、实例一

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
        <style>
            .hide{
                display: none;
            }
            .menu{
                height: 38px;
                background-color: #eeeeee;
                line-height: 38px;
            }
            .active{
                background-color: brown;
            }
            .menu .menu-item{
                float: left;
                border-right: 1px solid red;
                padding: 0 5px;     /*上下边距为0,左右边距为5*/
                cursor: pointer;    /*小手指*/
            }
            .content{
                min-height: 100px;
                border: 1px solid #eeeeee;
            }
        </style>
    </head>
    <body>
        <div style="margin: 0 auto; 700px;">
            <div class="menu">
                <div a="1" class="menu-item active">耳机</div>
                <div a="2" class="menu-item">键盘</div>
                <div a="3" class="menu-item">鼠标</div>
            </div>
            <div class="content">
                <div b="1">内容一</div>
                <div b="2" class="hide">内容二</div>
                <div b="3" class="hide">内容三</div>
            </div>
        </div>
        <script src="../jquery-1.12.4.js"></script>
        <script>
            $(".menu-item").click(function(){
               $(this).addClass('active').siblings().removeClass('active');
               var target = $(this).attr('a');      //获取this的a属性对应的值
               $('.content').children("[b='"+ target +"']").removeClass('hide').siblings().addClass('hide');
            });
        </script>
    </body>
    </html>
    属性操作Demo

    七、jQuery文档处理

    append        在最后面添加
    prepend        在最前面添加元素
    after        在每个匹配的元素之后插入内容    $("p").after("<b>Hello</b>");
    before        在每个匹配的元素之前插入内容     $("p").before("<b>Hello</b>");
    
    remove        删除
    empty        把所有段落的子元素(包括文本节点)删除        $("p").empty();
    
    clone        克隆

    7.1、实例一

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
        <input id="t1" type="text" />
        <input id="a1" type="button" value="添加" />
        <input id="a2" type="button" value="删除" />
        <input id="a3" type="button" value="复制" />
    
        <ul id="u1">
            <li>0</li>
            <li>1</li>
            <li>2</li>
        </ul>
    
        <script src="../jquery-1.12.4.js"></script>
        <script>
            //添加功能
            $('#a1').click(function(){
                //思路:   1.获取输入框内的内容;2.将内容添加到列表中
                var text = $('#t1').val();
                var temp = "<li>" + text + "</li>";
                $('#u1').append(temp);
            });
    
            //删除功能
            $('#a2').click(function(){
               var index = $("#t1").val();
               $('#u1 li').eq(index).remove();
            });
    
            //复制功能
            $('#a3').click(function(){
                var index = $('#t1').val();
                var v = $("#u1 li").eq(index).clone();
                $('#u1').append(v);
            })
        </script>
    </body>
    </html>
    文档处理实例

    八、jQuery CSS操作

    $('t1').css('样式名称', '样式值')

    8.1、实例一

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
        <style>
            .container{
                padding: 50px;
                border: 1px solid #dddddd;
            }
            .item{
                position: relative;
                width: 30px;
            }
        </style>
    </head>
    <body>
        <div class="container">
            <div class="item">
                <span></span>
            </div>
        </div>
    
        <div class="container">
            <div class="item">
                <span></span>
            </div>
        </div>
    
        <div class="container">
            <div class="item">
                <span></span>
            </div>
        </div>
    
        <div class="container">
            <div class="item">
                <span></span>
            </div>
        </div>
        <script src="jquery-1.12.4.js"></script>
        <script>
            $('.item').click(function(){
                //this 相当于<div class="item">
                console.log(this);
                AddFavor(this);
            });
    
            function AddFavor(self){
                //DOM对象
                var fontSize = 15;
                var top = 0;
                var right = 0;
                var opacity = 1;
    
                var tag = document.createElement('span')
                //使用jQuery给tag设置css属性
                $(tag).text('+1');
                $(tag).css('color','green');
                $(tag).css('position','absolute');
                $(tag).css('fontSize',fontSize + 'px');
                $(tag).css('right',right + 'px');
                $(tag).css('top', top + 'px');
                $(tag).css('opacity', opacity);
                $(self).append(tag); //将新建的<span>标签加入到<div>标签中
    
                var obj = setInterval(function(){
                    fontSize = fontSize + 10;
                    top = top - 10;
                    right = right - 10;
                    opacity = opacity - 0.1;
                    //重新给CSS属性赋值
                    $(tag).css('fontSize', fontSize+'px');
                    $(tag).css('right', right + 'px');
                    $(tag).css('top', top + 'px');
                    $(tag).css('opacity', opacity);
                    if(opacity < 0){
                        clearInterval(obj);
                        $(tag).remove();
    
                    }
                }, 40);
            }
        </script>
    </body>
    </html>
    点赞实例

    九、jQuery 位置操作

    ① offset(获取和设置匹配元素在整个html的相对坐标)

    <div id="i1"></div>
        <div style="height: 100px;100px;overflow: auto">
            <p>asdf</p><p>asdf</p><p>asdf</p><p>asdf</p><p>asdf</p><p>asdf</p><p>asdf</p>
            <p>asdf</p><p>asdf</p><p>asdf</p><p>asdf</p><p>asdf</p><p>asdf</p><p>asdf</p>
            <p>asdf</p><p>asdf</p><p>asdf</p><p>asdf</p><p>asdf</p><p>asdf</p><p>asdf</p>
        </div>
    <div id="i2"></div>
    <div style="height: 1000px;"></div>
    
    # 获取偏移量
    > $('#i2').offset()
    < Object {top: 108, left: 8}
    > $('#i2').offset().top
    < 108
    > $('#i2').offset().left
    < 8
    > $('#i2').offset({top:100,left:300})
    < [<div id=​"i2" style=​"position:​ relative;​ top:​ -8px;​ left:​ 292px;​> ">​</div>​]
    < $('#i2').offset()
    > Object {top: 100, left: 300}
    获取和设置相对坐标

     position(获取匹配元素相对父元素的坐标)

    <div style="height: 200px">000</div>
    <div style="position: relative">
        <div style="height: 100px">123</div>
        <div id="i1" style="position: absolute">456</div>
    </div>
    
    > $('#i1').position()
    < Object {top: 100, left: 0}
    > $('#i1').position().top
    < 100
    获取相对父元素的坐标

    ③ scrollTop(获取和设置滚动条到顶部的坐标)

    <div style="height: 100px;100px;overflow: auto">
        <p>asdf</p><p>asdf</p><p>asdf</p><p>asdf</p><p>asdf</p><p>asdf</p><p>asdf</p>
        <p>asdf</p><p>asdf</p><p>asdf</p><p>asdf</p><p>asdf</p><p>asdf</p><p>asdf</p>
        <p>asdf</p><p>asdf</p><p>asdf</p><p>asdf</p><p>asdf</p><p>asdf</p><p>asdf</p>
    </div>
    <div style="height: 1000px;"></div>
    
    # 获取滚动条坐标
    > $(window).scrollTop()
    < 0
    > $('div').scrollTop()
    < 424
    
    # 设置滚动条坐标
    > $(window).scrollTop(200)
    < [Window]
    > $(window).scrollTop()
    < 200
    滚动条到顶部的坐标

    ④ scrollLeft(获取和设置滚动条到左侧的坐标)

    <div style="height: 100px;100px;overflow: auto">
        <p>asdf</p><p>asdf</p><p>asdf</p><p>asdf</p><p>asdf</p><p>asdf</p><p>asdf</p>
        <p>asdf</p><p>asdf</p><p>asdf</p><p>asdf</p><p>asdf</p><p>asdf</p><p>asdf</p>
        <p>asdf</p><p>asdf</p><p>asdf</p><p>asdf</p><p>asdf</p><p>asdf</p><p>asdf</p>
    </div>
    <div style="height: 1000px; 2000px"></div>
    
    # 获取
    > $(window).scrollLeft()
    < 0
    # 设置
    > $(window).scrollLeft(300)
    < [Window]
    > $(window).scrollLeft()
    < 300
    滚动条到左侧的坐标

    三、尺寸

    1
    2
    3
    4
    5
    6
    height        取得匹配元素当前计算的高度值(px)
    innerHeight        获取第一个匹配元素内部区域高度(包括补白、不包括边框)
    outerHeight        获取第一个匹配元素外部高度(默认包括补白和边框)
    width        取得第一个匹配元素当前计算的宽度值(px)
    innerWidth        获取第一个匹配元素内部区域宽度(包括补白、不包括边框)
    outerWidth        获取第一个匹配元素外部宽度(默认包括补白和边框)

    十、jQuery 事件操作

    一、事件处理

    ① on(在选择元素上绑定一个或多个事件的事件处理函数)

    1
    2
    3
    4
    5
    # 点击p标签打印标签内容
     
    $("p").on("click", function(){
    alert( $(this).text() );
    });

    ② off(off方法移除用on绑定的事件处理程序)

    1
    2
    3
    # 移出on绑定的事件
     
    $("p").off()

    ③ bind(为每个匹配元素的特定事件绑定事件处理函数)

    1
    2
    3
    4
    5
    # 点击p标签打印标签内容
     
    $("p").bind("click", function(){
      alert( $(this).text() );
    });

    二、事件委派

    ① delegate(指定的元素(属于被选元素的子元素)添加一个或多个事件处理程序,并规定当这些事件发生时运行的函数)

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    #使用 delegate() 方法的事件处理程序适用于当前或未来的元素(比如由脚本创建的新元素)--关键
     
    # 当点击div的button标签时,隐藏或显示 p 元素
    div style="
    <p>这是一个段落。</p>
    <button>请点击这里</button>
    </div>
     
    $("div").delegate("button","click",function(){
      $("p").slideToggle();
    });

    ② undelegat(删除由 delegate() 方法添加的一个或多个事件处理程序)

    1
    2
    3
    # 从p元素删除由 delegate() 方法添加的所有事件处理器
     
    $("p").undelegate();

    三、事件

    ① click(给元素绑定事件,点击触发函数调用执行)

    1
    2
    3
    # 所有的p标签点击后隐藏
     
    $("p").click( function () { $(this).hide(); });

    十一、jQuery拓展

    /**
     * Created by alex on 2016/11/26.
     */
    
    
    status = 1;
    
    $.extend({
       'wangsen': function () {
           return 'sb';
       }
    });
    plugin1.js
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
    
        <script src="jquery-1.12.4.js"></script>
        <script src="plugin1.js"></script>
        <script>
            var v = $.wangsen();
            alert(v);
    //        $('#i1').css()
    //        $.ajax()
            // jquery扩展
    //        $.fn.extend({
    //            "hanyang": function () {
    //                return 'db';
    //            }
    //        });
    //        var v = $('#i1').hanyang();
    //        alert(v);
    
    //        $.extend({
    //            'wangsen': function () {
    //                return 'sb';
    //            }
    //        });
    //        var v = $.wangsen();
    //        alert(v);
        </script>
    
    </body>
    </html>
    jQuery拓展

    十二、jQuery练习

    <!DOCTYPE html>
    <html>
    <head lang="en">
        <meta charset="UTF-8">
        <title></title>
    </head>
    <body>
        <div style="border: 1px solid #ddd; 600px;position: absolute;">
            <div id="title" style="background-color: black;height: 40px;"></div>
            <div style="height: 300px;"></div>
        </div>
    <script type="text/javascript" src="../jquery-1.12.4.js"></script>
    <script>
        $(function(){
            $('#title').mouseover(function(){
                $(this).css('cursor','move');
            });
            $("#title").mousedown(function(e){
                //console.log($(this).offset());
                var _event = e || window.event;
                var ord_x = _event.clientX;
                var ord_y = _event.clientY;
    
                var parent_left = $(this).parent().offset().left;
                var parent_top = $(this).parent().offset().top;
    
                $('#title').on('mousemove', function(e){
                    var _new_event = e || window.event;
                    var new_x = _new_event.clientX;
                    var new_y = _new_event.clientY;
    
                    var x = parent_left + (new_x - ord_x);
                    var y = parent_top + (new_y - ord_y);
    
                    $(this).parent().css('left',x+'px');
                    $(this).parent().css('top',y+'px');
    
                })
            });
            $("#title").mouseup(function(){
                $("#title").off('mousemove');
            });
        })
    </script>
    </body>
    </html>
    可以随鼠标移动的条框
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
    <input id="t1" type="text" />
    <input id="a1" type="button" value="添加" />
    <ul id="u1">
        <li>1</li>
        <li>2</li>
    </ul>
    <script src="../jquery-1.12.4.js"></script>
        <script>
            $('#a1').click(function () {
                var v = $('#t1').val();
                var temp = "<li>" + v + "</li>";
                $('#u1').append(temp);
            });
            // 新添加的li不能执行
    //        $('ul li').click(function () {
    //            var v = $(this).text();
    //            alert(v);
    //        })
            // 新添加的li不能执行
    //        $('ul li').bind('click',function () {
    //            var v = $(this).text();
    //            alert(v);
    //        })
            // 新添加的li不能执行
    //        $('ul li').on('click', function () {
    //            var v = $(this).text();
    //            alert(v);
    //        })
    
            // 新添加的li能执行
            $('ul').delegate('li','click',function () {
                var v = $(this).text();
                alert(v);
            })
    
        </script>
    </body>
    </html>
    delegate绑定未来元素.html
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
        <a onclick="return ClickOn()" href="https://home.cnblogs.com/u/lianzhilei/">走你1</a>
    
        <a id="i1" href="https://home.cnblogs.com/u/lianzhilei/">走你2</a>
        <script src="../jquery-1.12.4.js"></script>
        <script>
            function ClickOn() {
                alert(123);
                return true;
            }
            $('#i1').click(function () {
                alert(456);
                return false;
            })
        </script>
    </body>
    </html>
    click绑定多个事件.html
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
        <style>
            .error{
                color: red;
            }
        </style>
    </head>
    <body>
        <form id="f1" action="s5编辑框.html" method="POST">
            <div><input name="n1" tex = "用户名" type="text" /></div>
            <div><input name="n2" tex = "密码" type="password" /></div>
            <div><input name="n3" tex = "邮箱" type="text" /></div>
            <div><input name="n4" tex = "端口" type="text" /></div>
            <div><input name="n5" tex = "IP" type="text" /></div>
    
            <input type="submit" value="提交" />
        </form>
        <script src="../jquery-1.12.4.js"></script>
        <script>
            // 当页面框架加载完毕后,自动执行
    //        $(function(){
    //            $.Login('#f1')
    //        });
    //
            $(function(){
                // 当页面所有元素完全加载完毕后,执行
                $(':submit').click(function () {
    
                    $('.error').remove();
                    var flag = true;
                    $('#f1').find('input[type="text"],input[type="password"]').each(function () {
                        var v = $(this).val();
                        var n = $(this).attr('tex');
    
                        if(v.length <= 0){
                            flag = false;
                            var tag = document.createElement('span');
                            tag.className = "error";
                            tag.innerHTML = n + "必填";
                            $(this).after(tag);
                            // return false;
                        }
                    });
                    console.log(flag);
                    return flag;
    
            });
            });
    
        </script>
    </body>
    </html>
    表单验证

    后台管理编辑框 (重要)

    $(function(){
        BindSingleCheck('#edit_mode', '#tb1');
    });
    
    function BindSingleCheck(mode, tb){
    
        $(tb).find(':checkbox').bind('click', function(){
            var $tr = $(this).parent().parent();
            if($(mode).hasClass('editing')){
                if($(this).prop('checked')){
                    RowIntoEdit($tr);
                }else{
                    RowOutEdit($tr);
                }
            }
        });
    }
    
    function CreateSelect(attrs,csses,option_dict,item_key,item_value,current_val){
        var sel= document.createElement('select');
        $.each(attrs,function(k,v){
            $(sel).attr(k,v);
        });
        $.each(csses,function(k,v){
            $(sel).css(k,v);
        });
        $.each(option_dict,function(k,v){
            var opt1=document.createElement('option');
            var sel_text = v[item_value];
            var sel_value = v[item_key];
    
            if(sel_value==current_val){
                $(opt1).text(sel_text).attr('value', sel_value).attr('text', sel_text).attr('selected',true).appendTo($(sel));
            }else{
                $(opt1).text(sel_text).attr('value', sel_value).attr('text', sel_text).appendTo($(sel));
            }
        });
        return sel;
    }
    
    STATUS = [
        {'id': 1, 'value': "在线"},
        {'id': 2, 'value': "下线"}
    ];
    
    BUSINESS = [
        {'id': 1, 'value': "车上会"},
        {'id': 2, 'value': "二手车"}
    ];
    
    function RowIntoEdit($tr){
        $tr.children().each(function(){
            if($(this).attr('edit') == "true"){
                if($(this).attr('edit-type') == "select"){
                    var select_val = $(this).attr('sel-val');
                    var global_key = $(this).attr('global-key');
                    var selelct_tag = CreateSelect({"onchange": "MultiSelect(this);"}, {}, window[global_key], 'id', 'value', select_val);
                    $(this).html(selelct_tag);
                }else{
                    var orgin_value = $(this).text();
                    var temp = "<input value='"+ orgin_value+"' />";
                    $(this).html(temp);
                }
    
            }
        });
    }
    
    function RowOutEdit($tr){
        $tr.children().each(function(){
            if($(this).attr('edit') == "true"){
                if($(this).attr('edit-type') == "select"){
                    var new_val = $(this).children(':first').val();
                    var new_text = $(this).children(':first').find("option[value='"+new_val+"']").text();
                    $(this).attr('sel-val', new_val);
                    $(this).text(new_text);
                }else{
                    var orgin_value = $(this).children().first().val();
                    $(this).text(orgin_value);
                }
    
            }
        });
    }
    
    function CheckAll(mode, tb){
        if($(mode).hasClass('editing')){
    
            $(tb).children().each(function(){
    
                var tr = $(this);
                var check_box = tr.children().first().find(':checkbox');
                if(check_box.prop('checked')){
    
                }else{
                    check_box.prop('checked',true);
    
                    RowIntoEdit(tr);
                }
            });
    
        }else{
    
            $(tb).find(':checkbox').prop('checked', true);
        }
    }
    
    function CheckReverse(mode, tb){
    
        if($(mode).hasClass('editing')){
    
            $(tb).children().each(function(){
                var tr = $(this);
                var check_box = tr.children().first().find(':checkbox');
                if(check_box.prop('checked')){
                    check_box.prop('checked',false);
                    RowOutEdit(tr);
                }else{
                    check_box.prop('checked',true);
                    RowIntoEdit(tr);
                }
            });
    
    
        }else{
            //
            $(tb).children().each(function(){
                var tr = $(this);
                var check_box = tr.children().first().find(':checkbox');
                if(check_box.prop('checked')){
                    check_box.prop('checked',false);
                }else{
                    check_box.prop('checked',true);
                }
            });
        }
    }
    
    function CheckCancel(mode, tb){
        if($(mode).hasClass('editing')){
            $(tb).children().each(function(){
                var tr = $(this);
                var check_box = tr.children().first().find(':checkbox');
                if(check_box.prop('checked')){
                    check_box.prop('checked',false);
                    RowOutEdit(tr);
    
                }else{
    
                }
            });
    
        }else{
            $(tb).find(':checkbox').prop('checked', false);
        }
    }
    
    function EditMode(ths, tb){
        if($(ths).hasClass('editing')){
            $(ths).removeClass('editing');
            $(tb).children().each(function(){
                var tr = $(this);
                var check_box = tr.children().first().find(':checkbox');
                if(check_box.prop('checked')){
                    RowOutEdit(tr);
                }else{
    
                }
            });
    
        }else{
    
            $(ths).addClass('editing');
            $(tb).children().each(function(){
                var tr = $(this);
                var check_box = tr.children().first().find(':checkbox');
                if(check_box.prop('checked')){
                    RowIntoEdit(tr);
                }else{
    
                }
            });
    
        }
    }
    edit_row.js
    <!DOCTYPE html>
    <html>
    <head lang="en">
        <meta charset="UTF-8">
        <title></title>
        <style>
            .edit-mode{
                background-color: #b3b3b3;
                padding: 8px;
                text-decoration: none;
                color: white;
            }
            .editing{
                background-color: #f0ad4e;
            }
        </style>
    </head>
    <body>
    
        <div style="padding: 20px">
            <input type="button" onclick="CheckAll('#edit_mode', '#tb1');" value="全选" />
            <input type="button" onclick="CheckReverse('#edit_mode', '#tb1');" value="反选" />
            <input type="button" onclick="CheckCancel('#edit_mode', '#tb1');" value="取消" />
    
            <a id="edit_mode" class="edit-mode"   onclick="EditMode(this, '#tb1');">进入编辑模式</a>
    
        </div>
        <table border="1">
            <thead>
            <tr>
                <th>选择</th>
                <th>主机名</th>
                <th>端口</th>
                <th>状态</th>
            </tr>
            </thead>
            <tbody id="tb1">
                <tr>
                    <td><input type="checkbox" /></td>
                    <td edit="true">v1</td>
                    <td>v11</td>
                    <td edit="true" edit-type="select" sel-val="1" global-key="STATUS">在线</td>
                </tr>
                <tr>
                    <td><input type="checkbox" /></td>
                    <td edit="true">v1</td>
                    <td>v11</td>
                    <td edit="true" edit-type="select" sel-val="2" global-key="STATUS">下线</td>
                </tr>
                <tr>
                    <td><input type="checkbox" /></td>
                    <td edit="true">v1</td>
                    <td>v11</td>
                    <td edit="true" edit-type="select" sel-val="1" global-key="STATUS">在线</td>
                </tr>
            </tbody>
        </table>
    
        <script type="text/javascript" src="jquery-1.8.2.min.js"></script>
        <script type="text/javascript" src="edit_row.js"></script>
    
        <script>
            /*
             监听是否已经按下control键
             */
            window.globalCtrlKeyPress = false;
    
            window.onkeydown = function(event){
                if(event && event.keyCode == 17){
                    window.globalCtrlKeyPress = true;
                }
            };
    
            window.onkeyup = function(event){
                if(event && event.keyCode == 17){
                    window.globalCtrlKeyPress = false;
                }
            };
    
            /*
             按下Control,联动表格中正在编辑的select
             */
            function MultiSelect(ths){
                if(window.globalCtrlKeyPress){
                    var index = $(ths).parent().index();
                    var value = $(ths).val();
                    $(ths).parent().parent().nextAll().find("td input[type='checkbox']:checked").each(function(){
                        $(this).parent().parent().children().eq(index).children().val(value);
                    });
                }
            }
        </script>
    
    </body>
    </html>
    edit_row.html

    参考文档-》》https://www.cnblogs.com/lianzhilei/p/6110866.html

    参考文档-》》http://jquery.cuishifeng.cn/submit_1.html

  • 相关阅读:
    【机器学习】均方误差(MSE)和均方根误差(RMSE)和平均绝对误差(MAE)
    python自动化测试框架nose
    python单元测试之unittest框架使用总结
    【flask】flask讲解
    Python查询手机号码归属地几种方法
    数据库的备份与恢复
    python中OrderedDict的使用
    python struct 结构体
    【Linux】linux-nfs挂载
    【机器学习】方差为何除以n-1
  • 原文地址:https://www.cnblogs.com/replaceroot/p/9874597.html
Copyright © 2011-2022 走看看