zoukankan      html  css  js  c++  java
  • javaScript之jQuery框架

    一、jQuery简介
     
      jQuery是一个快速、简洁的JavaScript框架,是继Prototype之后又一个优秀的JavaScript代码库(或JavaScript框架)。jQuery设计的宗旨是“write Less,Do More”,即倡导写更少的代码,做更多的事情。它封装JavaScript常用的功能代码,提供一种简便的JavaScript设计模式,优化HTML文档操作、事件处理、动画设计和Ajax交互。
      jQuery的核心特性可以总结为:具有独特的链式语法和短小清晰的多功能接口;具有高效灵活的css选择器,并且可对CSS选择器进行扩展;拥有便捷的插件扩展机制和丰富的插件。jQuery兼容各种主流浏览器,如IE 6.0+、FF 1.5+、Safari 2.0+、Opera 9.0+等。
    使用jQuery
        jQuery类似python里面的模块,它封装了DOM/BOM/JavaScriptd,所以我们在使用jQuery时需引入。
    <script src="jquery.js"></script>
    版本选择
         jQuery版本有很多,1.*,2.*,3.*,一般我们选择1.*的最高版本,因为比较稳定,兼容性好。
     
    jQuery对象和Dom对象的转换
    • jquery对象[索引] => Dom对象
    • $(Dom对象)  => jquery对象

    学习参考网址:http://jquery.cuishifeng.cn/

    二、选择器
     
     1.id选择器
    $("id")

    2.class选择器

    $(".a1")

    3.标签选择器

    $("div")

    4.组合选择器

    $("#a1,.c1,div") //逗号分隔,只要匹配都找到

    5.层级选择器

    $(".a1 a")//查找class=“a1”下面所有的a标签,子子孙孙查询
    
    $(".a1>a")//查找class=“a1”下面孩子中的a标签,只找孩子

     6.基本选择器

    $(".header>a:first")// :first 找到标签的第一个
    $(".header>a:last")// :last 找到标签的最后一个
    $(".header>a:eq")// :eq(index) 匹配索引取标签
    $(".header>a:even")//:even 找到标签的最后一个匹配所有索引值为偶数的元素,从 0 开始计数
    
    $(".header>a:odd")//:odd 找到标签的最后一个匹配所有索引值为基数的元素,从 1 开始计数

    7.属性选择器

    $("[name]")//查找所有具有name熟悉的标签
    $("div[name]")//查找所有含有name属性的div标签
    $("div[name="wd"]") //查找所有name=wd的div标签
    $("[name='wd']")//查找所有name=wd的标签

     8.对于input系列选择器(匹配所有 input, textarea, select 和 button 元素)

    $(":input")//找所有input标签
    $(":text")//匹配所有input的单行文本框
    $(":passwordt")//匹配所有input的type=password
    $(":enabled")  //默认都是enabled,disabled代表不可输出或不可点击
    $(":disabled")
    $(":checked")
    三、筛选

     当我们利用选择器将所需的元素查找出来时,还可以在利用筛选器进行筛选.

    1.筛选

    利用jquery查找到了元素后,在对找到的集合进行筛选

    eq(index|-index)//按索引筛选,负数代表倒数,例如:eq(1),eq(-1)
    first()//筛选第一个
    last()//筛选最后一个
    hasclass()//筛选含有某种样式
    filter(expr|jqobj|ele|fn)//筛选出与指定表达式匹配的元素集合,例如$("div").filter(".header,#a1"),多个选择器可以使用逗号隔开

    find(expr|jqobj|ele)//从子子孙孙中筛选出与指定表达式匹配的元素集合,例如$("div").find("#a1")

    示例:

    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
        <style>
            .header{
                color: red;
            }
        </style>
    </head>
    <body>
    <div class="header" name="wd">name
        <a>1</a>
        <a class="header">2</a>
        <a>3</a>
        <span name="wd"></span>
    </div>
    <div id="a1" name="wd">age
    <span>
        <a id="c1">11</a>
        <a>22</a>
        <a>33</a>
    </span>
    </div>
    <div>name</div >
    <input type="text">
    <input type="password">
    <input type="checkbox">
    <input type="button">
    <script src="jquery.js"></script>
    <script>
        var tag1=$("span> a").eq(1);//过滤找到集合的中索引等于1的
        var tag2=$("span>a").first();//过滤找到集合的第一个
        var tag3=$("span>a").last();//过滤找到集合的最后一个
        var tag4=$("span>a").filter("#c1");//过滤含有id=#c1
        var tag5=$("a").hasClass("header");//检查找到jquery对象是否含有样式,返回true/false
    </script>
    </body>
    </html>

     2.可见性筛选

    $('p:hidden).size(); //筛选出元素 p 隐藏的元素,size表示大小
    $('p:visible').size(); //元素 p 显示的元素
    注意::hidden 过滤器一般是包含的内容为:CSS 样式为 display:none、input 表单类型为type="hidden"和 visibility:hidden 的元素

    3.查找

    利用jquery查找到元素后,再进行查找

    children()       // 查找所有的孩子
    siblings()      // 所有的兄弟姐妹
    next()          // 下一个
    nextAll()        // 同一级后面的所有元素
    nextUntil()      // 下一个直到什么为止(不包含),就是一个区间
    prev()           // 上一个
    prevAll()        // 上面的所有同一级元素
    prevUntil()      // 上一个直到什么为止(不包含)
    parent()         // 父标签
    parents()        // 所有的父标签(祖祖辈辈)
    parentsUntil()   // 所有的父标签直到什么为止(不包含),区间 

    4.文档操作

    $(..).text()            //获取文本内容(和dom比较少了inner)
    $(..).text("wd”)        // 设置文本内容
    
    $(..).html()            // 获取内容(html格式)
    $(..).html("<a>wd</a>") // 设置内容(参数为html格式的字符串,也可以只是内容)
    
    $(..).val()            // 获取val的值(针对input系列、select等有value属性的)
    $(..).val(..)          // 设置val的值(针对input系列、select等有value属性的)

     5.样式操作

    addClass()        //添加一类样式
    removeClass()  // 移除一类样式
    toggleClass()   // 简化删除添加样式流程,如果存在(不存在)就删除(添加)一类样式

    6.属性操作

    //自定义属性
    $(..).attr('n')               // 获取属性值
    $(..).attr('n','v')           // 设置属性值
    $(..).removeAttr('n')        // 移除属性
    
    
    //chekbox,radio等
    $(..).prop('checked')          // 获取属性
    $(..).prop('checked', true)   // 设置属性


     7.文档处理

    append()    // 找到的标签每个追加(尾部)
    prepend()   // 标签内部开头
    
    after()      // 标签外部末尾(相当于增加兄弟,位置在后面)
    before()     // 标签外部开头(相当于增加兄弟,位置在前面)
    
    remove()     // 移除找到的标签
    empty()      // 清空找到的标签的内容
         
    clone()      // 克隆标签,克隆之后可用于添加到其他地方

    8.位置处理

    $('t1').css('样式名称', '样式值')//设置css样式
    
    // 位置相关
    $(window).scrollTop()        // 获取
    $(window).scrollTop(0)       //设置
    $(window).scrollLeft([val])
    
    offset().left                // 指定标签在html中的坐标
    offset().top                 // 指定标签在html中的坐标
    position()                   // 指定标签相对父标签(relative)标签的坐标
    
    height()                     // 获取某个元素的高度        
    innerHeight()               // 获取某个元素的高度 + 内边距 padding
    outerHeight()                // 获取某个元素的高度 + 内边距 padding + 边框 border
    outerHeight(true)            // 获取某个元素的高度 + 内边距 padding + 边框 border + 外边距 margin
    
    width()                      // 获取某个元素的宽度
    innerWidth()                 // 获取某个元素的宽度 + 内边距 padding
    outerWidth()                 // 获取某个元素的宽度 + 内边距 padding + 边框 border
    outerWidth(true)             //获取某个元素的宽度 + 内边距 padding + 边框 border + 外边距 margin

    示例:

    $('div').width(); //获取元素的长度,返回的类型为 number
    $('div').width(500); //设置元素长度,直接传数值,默认加 px
    $('div').width('500pt'); //同上,设置了 pt 单位
    $('div').width(function (index, value) { //index 是索引,value 是原本值
    return value - 500; //无须调整类型,直接计算
    });
    
    $('div').height(); //获取元素的高度,返回的类型为 number
    $('div').height(500); //设置元素高度,直接传数值,默认加 px
    $('div').height('500pt'); //同上,设置了 pt 单位
    $('div').height(function (index, value) { //index 是索引,value 是原本值
    return value - 1; //无须调整类型,直接计算
    });
    
    alert($('div').width()); //不包含
    alert($('div').innerWidth()); //包含内边距 padding
    alert($('div').outerWidth()); //包含内边距 padding+边框 border
    alert($('div').outerWidth(true)); //包含内边距 padding+边框 border+外边距 margin
    
    $('strong').offset().left; //相对于视口的偏移
    $('strong').position().left; //相对于父元素的偏移
    $(window).scrollTop(); //获取当前滚动条的位置
    $(window).scrollTop(300); //设置当前滚动条的位置

    9.样式操作

    $('div').css('color'); //获取元素行内 CSS 样式的颜色
    $('div').css('color', 'red'); //设置元素行内 CSS 样式颜色为红色
    //在需要设置多个样式的时候,我们可以传递多个 CSS 样式的键值对即可。
    $('div').css({
    'background-color' : '#ccc',
    'color' : 'red',
    'font-size' : '20px'
    });
    
    //除了行内 CSS 设置,我们也可以直接给元素添加 CSS 类,可以添加单个或多个,并且可以删除它。
    $('div').addClass('red'); //添加一个 CSS 类
    $('div').addClass('red bg'); //添加多个 CSS 类
    $('div').removeClass('bg'); //删除一个 CSS 类
    $('div').removeClass('red bg'); //删除多个 CSS 类
    $('div').click(function () { //当点击后触发
    $(this).toggleClass('red size'); //单个样式多个样式均可
    });
    //.toggleClass()方法的第二个参数可以传入一个布尔值, true 表示执行切换到 class 类, false表示执行回默认 class 类(默认的是空 class),运用这个特性,我们可以设置切换的频率。
    var count = 0;
    $('div').click(function () { //每点击两次切换一次 red
    $(this).toggleClass('red', count++ % 3 == 0);
    });
    四、jquery事件绑定及解绑

    1.事件绑定方式

    //普通方式,所有的js中把on去掉
    $('.c1').click(function(){
    
    })
    $('.c1').....
    
    //绑定函数方式
    $('.c1').bind('click',function(){
    })
    
    $('.c1').unbind('click',function(){
    
    })
    
    //委托方式,好处就是后在增加标签的时候,不用再进行绑定事件
    $('.c1').delegate('a', 'click', function(){
    
    })
    $('.c1').undelegate('a', 'click', function(){
    
    })
    
    //最基本方式, 其他都是基于该方式进行封装
    $('.c1').on('click', function(){
    
    })
    $('.c1').off('click', function(){
    
    })
    五、自执行函数应用以及事件相关

    1、页面框架加载完毕自动执行

    <script>
     $(function () {
            //js代码
     })
    </script>

    2、阻止事件发生(return false)

    当标签中含有绑定的事件时候,我们继续绑定事件,默认绑定事件后执行,在dom中需要加return

    //dom 示例
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
    <a onclick="return addsome()" href="https://www.baidu.com">搜索</a>
    <script src="jquery.js"></script>
    <script>
    function addsome() {
        alert(123);
        return false //该函数返回false阻止后面事件发生
    }
    </script>
    </body>
    </html>
    
    
    
    
    //jquery 示例
    
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
    <a  href="https://www.baidu.com">搜索</a>
    <script src="jquery.js"></script>
    <script>
    $('a').click(function () {
        alert(123);
        return false//阻止后续事件发生,return true 后续事件才能发生
    })
    </script>
    </body>
    </html>

    3、jquery扩展以及自执行函数应用

    jquery扩展:

    //方式1
    $.extend({ 'test':function(){ return 'wd'}
    })
    //调用
    $.test()
    
    //方式2
    $.fn.extend({'showname':function(){return 'wd'}
    })
    //调用时候需要加上选择器
    $(#a1').showname()

     4、自执行函数应用当多个扩展同时存在时候,为避免全局变量的冲突,可以加上自执行函数,将全局变量变为局部变量,这样可避免变量的冲突。

    //示例:
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
    <a  href="https://www.baidu.com">搜索</a>
    <script src="jquery.js"></script>
    <script>
    (function(arg) {
        var a = 'wd';
        arg.extend({
            'showname': function () {
                alert(a);
            }
        });
    })($);//将jquery作为参数传递进去
    $.showname()//调用
    </script>
    </body>
    </html>
    案例篇

     1、全选反选取消

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
    <input type="button" value="全选">
    <input type="button" value="取消">
    <input type="button" value="反选">
    <table border="1px solid #ddddd">
        <thead>
        <th>ip</th>
        <th>端口</th>
        <th>操作</th>
        </thead>
        <tbody>
        <tr>
            <td><input type="checkbox"></td>
            <td>10.0.0.230</td>
            <td>80</td>
            <td>添加</td>
        </tr>
        <tr>
            <td><input type="checkbox"></td>
            <td>10.0.0.231</td>
            <td>80</td>
            <td>添加</td>
        </tr>
        <tr>
            <td><input type="checkbox"></td>
            <td>10.0.0.232</td>
            <td>80</td>
            <td>添加</td>
        </tr>
    
        </tbody>
    </table>
    <script src="jquery.js"></script>
    <script>
        $('input[value="全选"]').click(checkAll);
        $('input[value="反选"]').click(reverse);
        $('input[value="取消"]').click(cancleAll);
        function checkAll() {
            $(':checkbox').prop('checked', true);
        }
        function cancleAll() {
           $(':checkbox').prop('checked',false);
        }
        function reverse() {
            $(':checkbox').each(function () {
    //           if(this.checked){
    //               this.checked=false;
    //           }
    //           else{
    //               this.checked=true;
    //           }//    普通方式
                this.checked=this.checked?false:true;//采用三元运算
            })
        }
    </script>
    </body>
    </html>
    View Code

    2、jquery版本tab菜单示例

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
        <style>
            .menu-left{
                height: 800px;
                 120px;
                background-color: #1c5a9c;
    
            }
            .menu-item{
                color: white;
                cursor: pointer;
            }
            .hidden{
                display: none;
            }
            .context{
                color: white;
            }
        </style>
    </head>
    <body style="margin: 0 auto">
    <div class="menu-left">
        <div class="menu-item">菜单1</div>
        <div class="context hidden" >内容1</div>
        <div class="menu-item">菜单2</div>
        <div class="context hidden">内容2</div>
        <div class="menu-item ">菜单3</div>
        <div class="context hidden">内容3</div>
    </div>
    <script src="jquery.js"></script>
    <script>
        $('.menu-item').click(function () {
            $(this).next().removeClass('hidden').siblings('.context').addClass('hidden');
        })
    </script>
    </body>
    </html>
    View Code

    3、jquery版本模态框1

    实现:通过索引获取值,可扩展性不高,不建议采用

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
        <style>
            .model{
                background-color: black;
                opacity: 0.6;
                position: fixed;
                top:0;
                right: 0;
                bottom:0;
                left:0;
                z-index: 9;
            }
            .hide{
                display:none;
            }
            .model-menu{
                height: 400px;
                560px;
                position: fixed;
                top:50%;
                right:50%;
                background-color:#dddddd;
                z-index: 10;
                margin-top: -200px;
                margin-right: -280px;
            }
        </style>
    </head>
    <body>
    <div>
        <input type="button" value="添加">
        <table border="1">
            <thead>
            <tr>
                <td>ip</td>
                <td>端口</td>
                <td rowspan="2">操作</td>
            </tr>
            </thead>
            <tbody>
            <tr>
                <td>10.0.0.230</td>
                <td>80</td>
                <td><input type="button" value="编辑"></td>
                <td><input type="button" value="删除"></td>
            </tr>
            <tr>
                <td>10.0.0.231</td>
                <td>81</td>
                <td><input type="button" value="编辑"></td>
                <td><input type="button" value="删除"></td>
            </tr>
            </tbody>
        </table>
    </div>
    <div class="model hide">
    </div>
    <div class="model-menu hide">
        <input type="text">
        <input type="text">
        <input type="button" value="取消">
    </div>
    <script src="jquery.js"></script>
    <script>
        $('input[value="添加"]').click(function () {
            $('.model,.model-menu').removeClass('hide');
        });
        $('input[value="取消"]').click(function () {
          $('.model,.model-menu').addClass('hide');
        });
        $('input[value="编辑"]').click(function () {
           $('.model,.model-menu').removeClass('hide');
           var port=$(this).parent().prevAll()[0].innerText;
           var ip=$(this).parent().prevAll()[1].innerText;
           $('.model-menu input[type="text"]')[0].value=ip;
           $('.model-menu input[type="text"]')[1].value=port;
        });
    </script>
    </body>
    </html>
    View Code

    4、jquery版本模态框2实现:通过自定义属性获取值,方便扩展;

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
        <style>
            .model{
                background-color: black;
                opacity: 0.6;
                position: fixed;
                top:0;
                right: 0;
                bottom:0;
                left:0;
                z-index: 9;
            }
            .hide{
                display:none;
            }
            .model-menu{
                height: 400px;
                560px;
                position: fixed;
                top:50%;
                right:50%;
                background-color:#dddddd;
                z-index: 10;
                margin-top: -200px;
                margin-right: -280px;
            }
        </style>
    </head>
    <body>
    <div>
        <input type="button" value="添加">
        <table border="1" name="table">
            <thead>
            <tr>
                <td>ip</td>
                <td>端口</td>
                <td rowspan="2">操作</td>
            </tr>
            </thead>
            <tbody>
            <tr>
                <td name="ip">10.0.0.230</td>
                <td name="port">80</td>
                <td><input type="button" value="编辑"></td>
                <td><input type="button" value="删除" class="del"></td>
            </tr>
            <tr>
                <td name="ip">10.0.0.231</td>
                <td name="port">81</td>
                <td><input type="button" value="编辑" ></td>
                <td><input type="button" value="删除" class="del" ></td>
            </tr>
            </tbody>
        </table>
    </div>
    <div class="model hide">
    </div>
    <div class="model-menu hide">
        <input type="text" target="ip">
        <input type="text" target="port">
        <input type="button" value="确定">
        <input type="button" value="取消">
    </div>
    <script src="jquery.js"></script>
    <script>
        $('input[value="添加"]').click(function () {
            $('.model,.model-menu').removeClass('hide');
        });
        $('input[value="取消"]').click(function () {
          $('.model,.model-menu').addClass('hide');
        });
        $('input[value="编辑"]').click(function () {
           $('.model,.model-menu').removeClass('hide');
           var ip=$(this).parent().prevAll().each(function () {
                var v=$(this).attr('name');//获取td的name属性
                var text=$(this).text();//获取当前td的内容
             var a=$('.model-menu input[target="'+v+'"]').val(text);//为输入框设置内容
           });
        });
        $('input[value="删除"]').click(function () {
            $(this).parent().parent().remove();//删除对应的行
        });
        $('input[value="确定"]').click(function () {
            var ip=$('.model-menu input[target="ip"]').val();
            var port=$('.model-menu input[target="port"]').val();
            if (ip==''||port==''){     //判断输入的内容是否为空
                alert('请输入相应的内容');
            }
            else{
                var td1=document.createElement('td');//创建元素,dom方式
                td1.innerText=ip;
                var td2=document.createElement('td');
                td2.innerText=port;
                var td3=$('<td><input type="button" value="编辑" ></td>');//创建元素,jquery方式
                var td4=$('<td><input type="button" value="删除" ></td>');
                var tr=document.createElement('tr');
                tr.append(td1);
                tr.append(td2);
                $(tr).append(td3);
                $(tr).append(td4);
                $('table[name="table"]').append(tr);
                $('.model,.model-menu').addClass('hide');
            }
        })
    </script>
    </body>
    </html>
    View Code

     5、点赞效果
    知识点:

    • 定时器setInterval:是标签一直变化
    • 透明度1->0:透明度逐渐变少
    • 标签positon:效果图和标签的关系是relative
    • 字体大小、位置:随着透明度的减少,字体位置逐渐变大
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
        <style>
            .item{
                padding: 50px;
                border: 1px;
            }
            .zan{
              cursor: pointer;
            }
            .z{
                position: relative;
                 30px;
            }
        </style>
    </head>
    <body>
    <div class="item">
        <div class="z">
            <span class="zan">赞</span>
        </div>
    </div>
    
    </body>
    <script src="../js/jquery.js"></script>
    <script>
        $('.zan').click(function () {
            var top=0;
            var right=0;
            var opacity=1;
            var fontsize=5;
            var tag=document.createElement('span');
            $(tag).css({'position':'absolute','color':'red'}).text('+1');
            $(this).parent().append($(tag));
            var obj=setInterval(function () {
               fontsize+=5;
               top-=10;
               right-=10;
               opacity-=0.2;
               $(tag).css('right',right+'px');
               $(tag).css('top',top+'px');
               $(tag).css('opacity',opacity);
               $(tag).css('fontSize',fontsize+'px');
                if (opacity<0){//当透明度为0的时候,应该删除标签,并取消定时器
                    clearInterval(obj);
                    $(tag).remove();
                }
            },100)
        })
    </script>
    </html>
    View Code

     6、表单验证

    表单验证中,如果函数返回true则表明表单通过,反之则不通过,不能提交;

    示例1

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
    <form action="1.html" method="post">
        <input type="text">
        <input type="submit" value="提交">
    </form>
    </body>
    <script src="../js/jquery.js"></script>
    <script>
        $('input[type=submit]').click(function () {
            var tag=$(this).prev().val();
            console.log(tag);
            if(tag.length>0){
                return true;//提交表单
    
            }else{
                alert('请输入内容');
                return false;
            }
        })
    </script>
    </html>
    View Code

    示例2

    当函数中存在循环如each,在循环中使用return使得循环退出,但是页面还是会提交,这时候需要使用标志位,当有数据不通过通过改变标志位来让页面不提交;

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
        <style>
            .error{
                color: red;
            }
        </style>
    </head>
    <body>
    <form action="1.html" method="post">
        <div><input type="text"></div>
        <div><input type="text"></div>
        <div><input type="text"></div>
        <div><input type="password"></div>
        <input type="submit" value="提交">
    </form>
    </body>
    <script src="../js/jquery.js"></script>
    <script>
        $('input[type=submit]').click(function () {
            $('.error').remove();//每次先清空提示
            var flag=true; //定义提交标志
            $(':text,:password').each(function () {
                if($(this).val().length<1){//输入为空时候的逻辑
                    var tag=$('<span class="error">必填</span>');
                    $(this).after(tag);
                    flag=false;
                    return false //这里的false是退出循环不在验证后面
                }
            });
            return flag
        })
    </script>
    </html>
    View Code
  • 相关阅读:
    java + jni + mingw实例开发(基于命令行窗口模式)
    OpenCv for Android
    Android图像处理实例教程
    eclipse使用技巧
    Android NDK开发实例教程
    Android开发的教程和资源
    JAVA安装,环境变量配置
    一些比较好的博客
    uwsgi启动Django项目时:unable to load app 0 (mountpoint='') (callable not found or import error) *** no app loaded. going in full dynamic mode ***
    robot中使用evaluate转化数据格式
  • 原文地址:https://www.cnblogs.com/wdliu/p/7489935.html
Copyright © 2011-2022 走看看