xone

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

jQuery是集成了DOM/BOM/JavaScript的类库

版本:
  1.x 1.12  //推荐
  2.x
  3.x

转换:

jquery对象[index]       ==>      Dom对象
Dom对象                 ==>      $(Dom对象)

 

一、查找元素

   DOM   

  繁琐   

  jQuery:

    选择器,直接找到某个或者某类标签   

  1. id

      $('#id')   

  2. class

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

  3. 标签

  <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>

  $('a')  // 找到所有的a标签

  4. 组合a

  <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>

  $('a')  //找到所有的a标签
  $('.c2')  //找到所有class为c2的标签
  $('a,.c2,#i10')  //找到所有a标签,所有class为c2的标签,所有id为i10的标签
$('div.c1') //找到所有div标签里class为c1的标签

  5. 层级

    $('#i10 a') //找到id为i10的子子孙孙里面的a标签
    $('#i10>a') //找到id为i10的儿子里面的a标签   

  6. 基本 

    :first
    $('#i2 a:first') //找到id为i2的子子孙孙里的a标签里的第一个     :last
    $('#i2 a:last') //找到id为i2的子子孙孙里的a标签里的最后一个
    :eq()
    $('#i2 a:eq(1)') //找到id为i2的子子孙孙里的a标签里的index为1的标签

  7. 属性

  $('[alex]')         // 具有alex属性的所有标签
  $('[alex="123"]')     // alex属性等于123的所有标签

  <input type='text'/>
  <input type='text'/>
  <input type='file'/>
  <input type='password'/>

  $("input[type='text']")    // input标签里面type属性等于text的所有标签
  $(':text')            // 表单选择器,获取input标签里type属性为text的所有标签

 

实例:

  多选,反选,全选

方式一:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

    <input type="button" value="全选" id="i1">
    <input type="button" value="反选" id="i2">
    <input type="button" value="取消" id="i3">

    <table id="tb1" border="1">
        <thead>
            <th>选项</th>
            <th>IP</th>
            <th>PORT</th>
        </thead>

        <tr>
            <td><input type="checkbox"></td>
            <td>10.0.1.2</td>
            <td>22</td>
        </tr>
        <tr>
            <td><input type="checkbox"></td>
            <td>10.0.1.2</td>
            <td>22</td>
        </tr>
        <tr>
            <td><input type="checkbox"></td>
            <td>10.0.1.2</td>
            <td>22</td>
        </tr>
        <tr>
            <td><input type="checkbox"></td>
            <td>10.0.1.2</td>
            <td>22</td>
        </tr>

    </table>
    <script src="jquery-1.12.4.js"></script>

    <script>

        $('#i1').click(function () {
            $('#tb1 :checkbox').prop('checked',true);  //设置id为tb1的所有input标签里type为checkbox的标签被选中
        });
        $('#i3').click(function () {
            $('#tb1 :checkbox').prop('checked',false);  //设置id为tb1的所有input标签里type为checkbox的标签取消选中
        });
        $('#i2').click(function () {
            $('#tb1 :checkbox').each(function () {    //对id为tb1的所有input标签里type为checkbox的标签执行each里面的函数
                if ($(this).prop('checked')){       //这里的this为DOM对象,用$(this)转为jQuery对象,然后获取当前选中状态。
                    $(this).prop('checked',false)    
                }else {
                    $(this).prop('checked',true)
                }
            })
        });
    </script>

</body>
</html>

方式二:

    <input type="button" value="全选" onclick="checkAll()">
    <input type="button" value="反选" onclick="reverseAll()">
    <input type="button" value="取消" onclick="cancelAll()">
    <table id="i1" border="1">
        <thead>
            <tr>
                <td>选项</td>
                <td>ip</td>
                <td>port</td>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td><input type="checkbox"></td>
                <td>10.0.1.1</td>
                <td>22</td>
            </tr>
            <tr>
                <td><input type="checkbox"></td>
                <td>10.0.1.1</td>
                <td>22</td>
            </tr>
            <tr>
                <td><input type="checkbox"></td>
                <td>10.0.1.1</td>
                <td>22</td>
            </tr>

        </tbody>
    </table>
    <script src="jquery-1.12.4.js"></script>
    <script>
        function checkAll(){
            $('#i1 :checkbox').prop('checked',true)
        }
        function cancelAll() {
            $('#i1 :checkbox').prop('checked',false)
        }
        function reverseAll() {
            $('#i1 :checkbox').each(function () {
                if(this.checked){
                    this.checked = false
                }else {
                    this.checked = true
                }
            })
        }

    </script>

筛选

    $('#i1').next()
    $('#i1').nextAll()

    $('#i1').nextUntil('#ii1')
    
    <div>
        <a>asdf</a>
        <a>asdf</a>
        <a id='i1'>asdf</a>
        <a>asdf</a>
        <a id='ii1'>asdf</a>
        <a>asdf</a>
    </div>
    
    $('#i1').prev()                #找到i1之前的一个元素
    $('#i1').prevAll()            #找到i1之前的所有元素
    $('#i1').prevUntil('#ii1')    #找到i1之前直到ii1的所有元素
    
    
    $('#i1').parent()            #找到i1的父元素
    $('#i1').parents()            #找到i1的所有祖先元素
    $('#i1').parentsUntil()        
    
    $('#i1').children()            #找到i1的孩子元素
    $('#i1').siblings()            #找到i1的兄弟元素
    $('#i1').find()                #找到i1的子孙元素
    $('li:eq(1)')
    $('li').eq(1)
    first()
    last()
    hasClass(class)  #判断属否存在class

左侧菜单

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>

    <style>
        .title{
            width: 200px;
            background-color: cornflowerblue;
        }
        .hide{
            display: none;
        }
        .content{
            min-height: 50px;
        }
    </style>

</head>
<body>

<div>
    <div class="item">
        <div class="title">标题一</div>
        <div class="content">内容</div>
    </div>
    <div class="item">
        <div class="title">标题二</div>
        <div class="content">内容2</div>
    </div>
    <div class="item">
        <div class="title">标题三</div>
        <div class="content">内容3</div>
    </div>
</div>
<script src="jquery-1.12.4.js"></script>
<script>
    $('.title').click(function () {
        $(this).next().removeClass('hide');
        var ii = $(this).parent().siblings().children('.content').addClass('hide');
    })
</script>
</body>
</html>

文本操作

    $(..).text()           # 获取文本内容
    $(..).text(“<a>1</a>”) # 设置文本内容
    
    $(..).html()
    $(..).html("<a>1</a>")
    
    $(..).val()       # 获取可以form提交的标签里的值
    $(..).val(..)       # 设置可以form提交的标签里的值

样式操作

    addClass
    removeClass
    toggleClass    //如果有就去除,没有就添加

属性操作:

    # 专门用于做自定义属性
    $(..).attr('n')        #显示属性为n的属性的值
    $(..).attr('n','v')    #不存在则创建,存在则更改,将属性为n的属性的值改为v
    $(..).removeAttr('n') #去除标签里的n属性
    
    <input type='checkbox' id='i1'  />
    
    
    # 专门用于chekbox,radio
    $(..).prop('checked')  
    $(..).prop('checked', true)
$(..).prop('name','myname') //只可以对一些内置的属性进行获取及定义 PS: index 获取索引位置

实例:编辑表单

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>

    <style>
        .hide{
            display: none;
        }
        .modal{
            position: fixed;
            top: 50%;
            left: 50%;
            width: 500px;
            height: 400px;
            margin-left: -250px;
            margin-top: -250px;
            background-color: #eeeeee;
            z-index: 10;
        }
        .shadow{
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            opacity: 0.6;
            background-color: black;
            z-index: 9;
        }
    </style>

</head>
<body>
        <a onclick="addElement();">添加</a>

    <table border="1" id="tb">
        <tr>
            <td target="hostname">1.1.1.11</td>
            <td target="port">80</td>
            <td target="ip">80</td>
            <td>
                <a class="edit">编辑</a> | <a class="del">删除</a>
            </td>
        </tr>
        <tr>
            <td target="hostname">1.1.1.12</td>
            <td target="port">80</td>
            <td target="ip">80</td>
            <td>
                <a class="edit">编辑</a> | <a class="del">删除</a>
            </td>
        </tr>
        <tr>
            <td target="hostname">1.1.1.13</td>
            <td target="port">80</td>
            <td target="ip">80</td>
            <td>
                <a class="edit">编辑</a> | <a class="del">删除</a>
            </td>
        </tr>
        <tr>
            <td target="hostname">1.1.1.14</td>
            <td target="port">80</td>
            <td target="ip">80</td>
            <td>
                <a class="edit">编辑</a> | <a class="del">删除</a>
            </td>

        </tr>
    </table>

    <div class="modal hide">
        <div>
            <input name="hostname" type="text"  />
            <input name="port" type="text" />
            <input name="ip" type="text" />
        </div>

        <div>
            <input type="button" value="取消" onclick="cancelModal();" />
            <input type="button" value="确定" onclick="confirmModal();" />
        </div>
    </div>

    <div class="shadow hide"></div>

    <script src="jquery-1.12.4.js"></script>
    <script>
        function  addElement() {
            $(".modal,.shadow").removeClass('hide');
        }
        function cancelModal() {
            $(".modal,.shadow").addClass('hide');
        }

//        找到点击目标行
        $('.edit').click(function () {

//            弹出编辑对话框
            $('.modal,.shadow').removeClass('hide');

//            找到当前编辑行要编辑的所有元素
            $(this).parent().prevAll().each(function () {

//                找到当前要编辑的元素的target属性值
                var target = $(this).attr('target');

//                找到当前要编辑的元素里的内容
                var text = $(this).text();


                $('.modal input[name="'+target+'"]').val(text)  //经典用法

            })


        })
        
    </script>

</body>
</html>

实例:切换菜单,内容也切换

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>

    <style>
        .menu{
            width: 700px;
            height: 38px;
        }

        .menu-item{
            line-height: 38px;
            float: left;
        }

        .active{
            background-color: darkcyan;
        }

        .content{
            min-height: 100px;
        }

        .hide{
            display: none;
        }

    </style>

</head>
<body>
    <div class="menu">
        <div class="menu-item active" a="1">标题一</div>
        <div class="menu-item" a="2">标题二</div>
        <div class="menu-item" a="3">标题三</div>
    </div>
    <div class="content">
        <div b="1">内容一</div>
        <div class="hide" b="2">内容二</div>
        <div class="hide" b="3">内容三</div>
    </div>

<script src="jquery-1.12.4.js"></script>
<script>
    $('.menu').children().click(function () {
        $(this).addClass('active').siblings().removeClass('active');
        var val = $(this).attr('a');
        $('.content').children('[b="'+ val +'"]').removeClass('hide').siblings().addClass('hide')
    })
    
</script>
</body>
</html>

文档处理

$(..).append(..)  // 添加内容到所有匹配到的标签内部的最后面。
$(..).prepend(..)     // 添加内容到所有匹配到的标签内部的最前面。
$(..).after(..)     // 添加内容到所有匹配到的标签的后面。
$(..).before(..)     // 添加内容到所有匹配到的标签的前面。
$('..').remove(..)  //清除所有匹配到的标签
$('..').empty(..)  //清除所有匹配到的标签里的内容
$('..').clone()  //克隆所有匹配到的标签,得到的结果是jQuery对象

jQuery没有创建标签的功能,需要用DOM进行创建

document.createElement("p")    //创建一个p标签

css

$("p").css("color");    // 显示style的color对应的值
$("p").css({ "color": "#ff0011", "background": "blue" }); // 设置style的样式
$("p").css("color","red");    // 设置style的样式

实例:点赞

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>

    <style>
        .container{
            border-bottom: 1px solid black;
            padding: 50px;
        }
        .item{
            width: 35px;
            position: relative;
        }

    </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 () {
        addFunc(this);
        console.log(1)
    });

    function addFunc(self) {
        var tag = document.createElement('span');
        $(tag).text('+1');
        var rigth = 0;
        var top = 0;
        var opacity = 1;
        var fontSize = 15;

        $(tag).css({'color':'green','position':'absolute','right':rigth+'px','top':top+'px','opacity':opacity,'font-size':fontSize+'px'});
        $(self).append(tag);

        var obj = setInterval(function () {
            rigth = rigth - 5;
            top = top - 5;
            opacity = opacity - 0.1;
            fontSize = fontSize + 5;
            $(tag).css({'color':'green','position':'absolute','right':rigth+'px','top':top+'px','opacity':opacity,'font-size':fontSize+'px'});

            if(opacity < 0){
                clearInterval(obj);
                console.log($(self));
                $(self).children().remove('[style]');
            }
        },100);

    }
    
</script>

</body>
</html>

位置

$("div").scrollTop();        // 显示当前div的位置
$("div").scrollTop(300); //设置div显示的位置

$(window).scrollTop();        // 显示当前窗口的位置
$(window).scrollTop(300); //设置当前窗口显示的位置


$("p:last").offset();   // 显示当前元素的 top 和 left 坐标。
$("p:last").offset({ top: 10, left: 30 });  // 设置当前元素的 top 和 left 坐标。

$("p:last").position()      // 获取指定标签相对父标签(relative)的坐标

$('.c1').height()        // 获取标签的纯高度
$('.c1').innerHeight()    // 获取纯高度 + padding*2
$('.c1').outerHeight()  // 获取纯高度 + 边框*2 + padding*2
$('.c1').outerHeight(true)    // 获取纯高度 + 边框*2 + padding*2 + margin*2

事件

click([[data],fn])      // 触发每一个匹配元素的click事件。
$("p").click( function () { $(this).hide(); })    // 将页面内所有段落点击后隐藏。

on可以对后生成的元素绑定事件。

on(events,[selector],[data],fn)    // events:一个或多个事件

$('#i2').on('click','li',function () {
    var v = $(this).text();
    alert(v);
})

阻止默认事件发生(a标签,input的submit,这些都会带默认事件)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<a id="i1" href="http://www.baidu.com">跳转</a>
<script src="jquery-1.12.4.js"></script>
<script>
    $('#i1').click(function () {
        alert(123);     // 先执行绑定事件,再执行默认事件
        return false    // 阻止默认事件发生
    })
</script>
</body>
</html>

希望查看页面立即执行的操作

                 $(function () {
                        ...
                  })

验证流程

前端js验证--->后端python验证

 

表单验证(浏览器级别做一些小处理)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
    <form id="f1" action="http://www.baidu.com" method="GET">
        <p><input type="text" name="username" require="true" /></p>
        <p><input type="password" name="password" require="true" min-len="6" max-len="18" /></p>
        <p><input type="text" name="phone" require="true" phone="true"  /></p>
        <input type="submit" value="提交" />
    </form>

    <script src="jquery-1.12.4.js"></script>
    <script>
        $(function () {
            checkValidate();
        });
        function checkValidate() {

            $('#f1').find(':submit').click(function () {
                $('#f1').find('span').remove();
                var flag = true;
                $('#f1').find(':text,:password').each(function () {
                    // $(this)代指每一个input标签
                    // 每一次执行都是一个标签
                    // 如果有某个标签的某一项不满足,调到下一个标签
                    var value = $(this).val();

                    var require = $(this).attr('require');
                    if(require){
                        if(value.length == 0){
                            var n = $(this).attr('name');
                            var errorTag = document.createElement('span');
                            errorTag.innerHTML = n + '输入不能为空';
                            $(this).after(errorTag);
                            flag = false;
                            // return true; // continue跳出当前循环开始下次循环
                            return false; // break跳出所有循环
                        }
                    }

                    var minLen = $(this).attr('min-len');
                    if(minLen){
                        var valueLen = value.length;
                        var minLen = parseInt(minLen);
                        if(valueLen < minLen){
                            var n = $(this).attr('name');
                            var errorTag = document.createElement('span');
                            errorTag.innerHTML = n + '太短了';
                            $(this).after(errorTag);
                            flag = false;
                            // return true; // continue
                            return false; // break;
                        }
                    }

                    var phone = $(this).attr('phone');
                    if(phone){
                        // value: asdfasdf
                        var re = /^\d+$/;
                        if(!re.test(value)){
                            var n = $(this).attr('name');
                            var errorTag = document.createElement('span');
                            errorTag.innerHTML = n + '格式错误';
                            $(this).after(errorTag);
                            flag = false;
                            // return true; // continue
                            return false; // break;
                        }
                    }
                });
                return flag;    // 判断是否执行默认事件
            })
        }
    </script>
</body>
</html>

jQuery扩展

<script src="jquery-1.12.4.js"></script>
<script>
    $.extend({    // 方式一
     'login':function (arg) {
         return arg
     }
    });
    var v = $.login(123);  // 方式一
    console.log(v);

    $.fn.extend({      // 方式二
        'login2':function (arg) {
            return arg
        }
    });

    var v2 = $('li').login2(456);  //方式二
    console.log(v2)
</script>

自定义jQuery组件:

plugin1.js

(function (arg) {
    
    var status = 1;
    arg.extend({    // 这里的arg是$
         'login':function (arg2) {
         return arg2
     }
    });
})($);  // 定义一个自执行函数,将jQuery作为参数传进去。

html

<!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 = $.login(123);
    console.log(v);
</script>
</body>
</html>

 

posted on 2017-03-06 11:27  周小百  阅读(249)  评论(0编辑  收藏  举报