javaee学习日记之java基础之jQuery

来源:互联网 发布:linux cron命令每周三 编辑:程序博客网 时间:2024/06/05 19:07

选择器
基本选择器

$(function(){//加载完节点执行$("#one").css("background","#bbffaa");//第一个id为one的元素并给定css样式$(".mini").css("background","red");//所有class名为mini的元素$("div").css("background","green");//所有div元素$("*").css("background","#bbffaa");//全部元素$("span,#two").css("background","#bbffaa");//span元素和id名为two的所有元素});

层次选择器

$("body div").css("background","red");//body元素下为div的全部元素$("body > div").css("background","green");//body元素下为div的全部子元素$(".one+div").css("background","blue");//class类名为one的下一个div节点(兄弟节点)$("#two~div").css("background","yellow");//id为two后的所有为div的兄弟节点

集合内基本选择器

//基本选择器            $('li:first');//获取所有li标签集合中第一个li标签            $('li:last');//获取所有li标签集合中最后一个li标签             $('li:not(.lis)');//获取所有li标签集合中除了class名为.lis的li标签not(可以是选择器)            $('li:even');//索引值为偶数的元素            $('li:odd');//索引值为奇数的元素            $('li:eq(2)');//集合中索引值为2的元素            $('li:gt(2)');//索引大于指定值的元素            $('li:lt(2)');//索引小于指定值的元素            $('h3');//选择所有的h3标签            $("*:animated");//选择有动画效果的元素            $(":root");//获取根节点元素(html)            $(":focus");//选择全部获得焦点的元素

内容选择器

$("li:contains(0)");//选择内容包含0的标签$("body:empty");//选择空标签,有回车符号(空格同样)的都不是空标签$("li:has(li)");//选择包含有指定标签的元素$("body:parent");//选择所有非空元素$("body:hidden");//选择所有隐藏的标签               $("body:visible");//选择所有显示状态到标签

属性选择器

$('li[class]');//选择具有class属性的元素$('li[class=lis-2]');//选择class= lis-2的元素$('li[class != lis-2]')//没有该属性的也会选择上(选择class不为lis-2的元素)$('li[ind ^= ind]');//选择属性值以某个字符或者字符串开头的元素(选择ind属性值以ind开头的元素)$('li[class $= -3]');//选择属性值以某个字符或者字符串结尾的元素(选择class属性值以-3结尾的元素)$('li[class *= -]');//选择属性值包含指定字符或者字符串的所有元素(选择class属性值包含-的元素)$('li[class ~= lis-2]');//选择指定属性用空格分隔的值中包含一个给定值的元素。(如class值为jj lis-2)$('li[ind |= data]');//选择指定属性值等于给定字符串或以该字符串为前缀(该字符串后跟一个连字符“-” )的元素。(如ind值为bb data)$('li[class][id]');//选择具有class属性和id属性的元素

子元素选择器

                总共两大类型,                a:-child为后缀的,不管指定的类型,直接遍历父级下的所有子元素                b:-of-type为后缀的,遍历父级下指定的类型的标签集合                1、选择第一个子元素,不管指定的类型是什么,永远选择第一个                $('ul li:first-child');//选择ul标签的后代标签中的第一个标签                2、选择最后一个子元素                var lis = $('ul li:last-child');//选择ul标签的后代标签中的第一个标签                3、选择自定义位置的选择器,从 1 开始计数                var lis = $('ul li:nth-child(2)');//选择ul标签的后代标签中的第2个标签                4、从后往前数第n个子元素                var lis = $('li:nth-last-child(4)');//选择ul标签的后代标签中的倒数第4个标签                5、选择没有任何兄弟节点的元素                var lis = $('p:only-child');//没有任何兄弟节点的元素(所有p标签中)                6、选择指定类型的第一个子元素                //var lis = $('.lis-9 h3:first-child');//class类名为lis-9的元素下第一个后代元素                var lis = $('.lis-9 h3:first-of-type');//class类名为lis-9的元素下第一个h3标签                7、选择指定类型的最后一个子元素                var lis = $('.lis-9 h3:last-of-type');//class类名为lis-9的元素下最后一个h3标签                8、选择指定类型的元素下的第n个子元素                var lis = $('.lis-9 h3:nth-child(2)');//class类名为lis-9的元素下第2个h3标签                9、选择指定类型的元素下的倒数第n个子元素                var lis = $('p:nth-last-of-type(2)');//所有p标签中倒数2个p标签                10、选择没有任何相同类型的兄弟节点的元素                var lis = $('i:only-of-type');//所有i标签中没有兄弟节点的元素

jQuery属性操作

                var p = $('p');                console.log(p)                /*                修改或添加属性 attr()                 //第一种写法,普通写法                p.attr('class','big')                p.attr('index','p1')                //第二种写法,连缀写法                p.attr('class','small').attr('index','p1');                //第三种写法,对象写法                p.attr({                    "class" : "big",                    "index" : "p1",                    "ps" : "ps"                })                移除属性 removeAttr()                console.log(p.removeAttr('class'))                p.removeAttr('class').attr('class','small')                class操作                添加class     addClass()                p.addClass('fontstyle')                移除class     removeClass()                p.removeClass('big').addClass('small')                toggleClass 如果有指定的样式,则去掉,如果没有,则添加                $('#but').click(function(){                    p.toggleClass('fontstyle')                })                内容获取与操作                获取:                var txt = p.html()                alert(txt)                设置:                $('#but').click(function(){                    $('p:first-child').html('这是改变之后的内容')                })                //带标签的话,会将标签进行解析                $('#but').click(function(){                    $('p:first-child').html('<i>这是i标签的内容</i>')                })                //text()与html()方法类似,只是不会解析字符串中的标签                $('#but').click(function(){                    $('p:first-child').text('<i>这是i标签的内容</i>')                })                获取input:text的值                $('#but').click(function(){                    alert($(':text').val())                    $(':text').val('内容已经改变')                })                //css样式的操作                //普通写法                p.css("color","chocolate").css("font-size",50)                //连缀写法                $('#box').css('width',500).css('height',150).css("background-color","#bcbcbc")                //对象第一种写法                $('#but').click(function(){                    $('#box').css({                        "width" : 500,                        "height" : 150,                        "background-color" : "#bcbcbc"                    })                })                //对象的第二种写法                $('#but').click(function(){                    $('#box').css({                        width : 500,                        height : 150,                        backgroundColor : "#bcbcbc"                    })
//获取与设置位置                offset  位置是相对于页面来定位的                var box = $('#box');                alert("left值为:"+box.offset().left+",top值为:"+box.offset().top)                //没有定位的元素设置offset的话,会自动添加position:relative                box.offset().left = "200px" //错误写法                box.offset({    //正确写法                    left : 200                })                box.offset({    //正确写法                    left : 200,                    top : 200                })                $('#but').click(function(){                    var box = $('#box');                    alert(box.offset().top)                })                  postion()获取位置,相对于上一个有定位的父级来获取位置,只能获取位置,不能设置位置                var box = $('.box');                var b2 = $('.box2');                $('button').click(function(){                    alert("left值为:"+b2.offset().left+",top值为:"+b2.offset().top);                    alert("left值为:"+b2.position().left+",top值为:"+b2.position().top);                })                var box = $('.box');                var b2 = $('.box2');                $('button').click(function(){                    b2.position({                        left : 200      //无效的写法                    })                })                //获取页面滚动出去的高度                window.onscroll = function(){                    console.log($(document).scrollTop())                }
                /*                //获取内容宽高 width                alert(wh.width())                获取可视宽高 width+padding                alert(wh.innerWidth())                //获取 width+padding+border                alert(wh.outerWidth())                //获取width+padding+border+margin                alert(wh.outerWidth(true))                //设置宽高                wh.width(400)                wh.width("400px")                */
                /*                1、查找子元素                $('.lis-9').children(":first").css('color','red');                $('.lis-9').children("p").css('color','red');                2、找最接近的一个指定的父级                $('p').closest('li').css('color','red');                3、找后代元素                lis.find("[class]").css('color','red');                4、找下一个兄弟节点                $('.lis-3').next().css('color','red');                lis.eq(7).next().css('color','red');                5、查找后面所有的兄弟节点                lis.eq(2).nextAll().css('color','red')                6、查找后面的所有的兄弟节点知道指定位置                lis.eq(2).nextUntil('[class]').css('color','red')                $('.p:first').nextUntil('i').css('color','red')                7、查找上一个兄弟节点                $('.lis-3').prev().css('color','red');                8、查找前面所有的兄弟节点                $('.lis-9').prevAll().css('color','red');                9、查找前面的所有的兄弟节点知道指定位置                $('i:last-child').prevUntil('p').css('color','red')                10、查找父级元素                $('i').parent().css('color','red')                11、查找所有上一级元素,直到html标签                $('i').parents().css('color','red')                12、查找所有上一级元素,直到指定位置位置(不包括指定位置)                $('i').parentsUntil('ul').css('color','red')                13、查找最近的一个有定位的父级元素                $('i').offsetParent().css('color','red')                14、查找所有的兄弟节点                $('.lis-3').siblings(":last-child").css('color','red')                15、向当前jQuery对象中追加新元素,可以是dom节点,也可以是jquery对象,不会改变原来的jQuery对象,会返回一个新的jQuery对象                console.log(lis.add($('p')))                console.log(lis)                16、把初始的操作对象添加到堆栈中                lis.eq(2).nextAll().css('color','red')                lis.eq(2).nextAll().addBack().css('color','red')                //观察两个语句的结果的不同                17、查找所有的子节点,包括文本节点、注释节点、标签节点等等                console.log(lis.children())                console.log(lis.contents())                18、回到初始操作的对象                *///              console.log(lis)                but.click(function(){                    console.log(lis.find("[class]").nextAll().css('color','red').end())                })
/*                过滤                1、eq() 查找jQuery对象中具体对象                lis.eq(5).css("color",'red')                2、first() 查找第一个                lis.first().css("color","red")                3last() 查找最后一个                lis.last().css("color","red")                4、hasClass() 判断一个jQuery对象中是否具有指定的class,只要集合中有一个具体对象包含了指定的class,就返回true                console.log(lis.hasClass('lis-3'))                5、filter() 过滤出指定选择器的jQuery对象                lis.filter(':lt(5)').css('color',"red")                6、is() 判断当前jQuery对象是否是指定的类型、选择器                lis3.is(":nth-of-type(3)")  参数为选择器                lis3.is("li")               参数为标签                lis3.is(lis)                参数为jQuery对象                lis3.is(function(){         参数为函数                    return "li";                })                7map() 给jQuery中的每个对象一个函数,参数只能是函数                but.click(function(){                    lis.map(function(){                        console.log($(this).html())                    })                })                8、has() 选择子元素有指定的选择器或者标签的元素                $('li').has('[class]').css('color','red')                $('li').has('p').css('color','red')                9not() 从jQuery对象移除指定的对象                var lisn = lis.not('[class]').css('color','red');                console.log(lisn)                var lisn = $('.lis-9').children().not('p').css('color','red');                console.log(lisn)                10、slice() 根据范围选择                lis.slice(2).css('color','red');                lis.slice(2,5).css('color','red');                lis.slice(-5,-2).css('color','red');

document对象与jQuery的相互转换

$(document.getElementById("is"));//将id为is的document对象转换成了jQuery对象var lis = $("#io")[0];//将id为io的jQuery对象转换成了document对象

表单选择器

$(":input");//选择document对象下所有input标签$(":text");//选择document对象下所有type为text的input标签$(":password");//选择document对象下所有type为password的input标签$(":radio");//选择document对象下所有type为radio的input标签表单属性$(":enabled") 选择可操作的表单标签$(":checked") 选择被选中的表单标签$(":selected") 选择下拉列表框被选中的option标签

插入文档

                1、内部插入元素,插入的内容是作为子元素存在的                //向后追加                append()                box.append('这是一个i标签')                box.append('<i>这是一个i标签</i>')                appendTo()                $('<i>这是另一个i标签</i>').appendTo(box)                //向前添加                prepend()                box.prepend('<i>这是一个i标签</i>')                box.prepend(function(){                    return "hello";                })                prependTo()                $('<i>这是另一个i标签</i>').prependTo(box);                2、外部插入元素,插入的内容是作为兄弟节点存在的                //向前添加兄弟节点                before()                box.before("<h1>这是before插入的h1标签</h1>")                insetBefore()                $("<h1>这是before插入的h1标签</h1>").insertBefore(box)                //往后面添加一个兄弟节点                box.after("<h1>这是after插入的h1标签</h1>")                insertAfter()                $("<h1>这是after插入的h1标签</h1>").insertAfter(box)                3、包裹                wrap() 为jQuery对象中的每一个对象单独添加一个父级                box.wrap("<div style='color: #ee0000;'></div>")                $('p').wrap('<h2></h2>')                unwrap() 不接受参数,移除父级元素                $('p').unwrap()                wrapAll() 为jQuery对象中所有元素添加一个公共的父级元素                $('p').wrapAll('<h2></h2>')                wrapInner() 是给自己的子元素重新添加一个父级,自己的位置提升                box.wrapInner('<h2></h2>')                4、替换                replaceWith() 将当前的对象替换成指定的内容                $('h4').replaceWith('<i>这是替换之后的i标签</i>');                replaceAll() 用当前的对象替换指定的对象                $('<i>这是i标签</i>').replaceAll('p')                5、删除                empty() 清空子元素,包括文本、标签、注释等所有子元素                box.empty()                remove() 移除指定对象,包括对象绑定的事件、属性全部移除,无法恢复                detach() 移除指定对象,对象绑定的事件、属性可以恢复                box.on('click',function(){                    alert('a')                })                var bb = box;                but.click(function(){                    //box.remove();                    box.detach();                    $('body').append(bb)                })                */                but.click(function(){                    var bb = box.clone();                    $('.box2').after(bb)                })
            //$.each(); 作用:遍历数组、类数组、对象。相当于JavaScript里面的for循环            var arr = [1,2,3,4,5,'a','b','c','d','e'];            var obj = {                "a" : "aaa",                "b" : "bbb",                "c" : "ccc"            }            //普通的for循环            /*            for (var i = 0; i < arr.length; i ++) {                console.log(arr[i])            }            for(var i in obj){                console.log(obj[i])            }            */            //jQuery方法            $.each(arr,function(i,v){                console.log(i,v)            })            $.each(obj,function(k,v) {                console.log(k,v)            });            $("ul li").click(function(){                $(this).index();//点击的li标签在ul的后代标签中的位置            });

事件处理

事件委托$("ul").on("click","li",function(){     alert("你点呀!");});//将ul下面的li的点击事件委托给ul来处理,其中li没有加事件,但在事件函数中使用this是处理的li元素,事件委托的优点:可动态的添加事件,方便!事件取消:$("ul").off("click");普通事件处理:$("div").hover(function(){alert("移入");},function(){alert("移出");});//鼠标移入移出事件(不会影响子元素)$(":text").change(function(){alert("内容改变了");});//内容改变事件$("div").click(function(){alert("点击");});//点击事件$(window).scroll(function(){    console.log('a');//滚动条滚动事件});resize() 页面可视区域大小改变时触发                    $(window).resize(function(){                        var box = $('.box');                        if ($(window).width() <= 600 ) {                            box.width($(window).width() - 20);                        }else{                            box.width(480);                        }                    });$(".te").keyup(function() {    alert("键盘弹起事件");});//键盘弹起事件$(".te").keydown(function() {    alert("键盘按下事件");});//键盘按下事件$("div").mousedown(function(){    alert("鼠标按下事件");});//鼠标按下事件$("div").mouseup(function(){alert("鼠标抬起事件");});$("div").mouseout(function(){alert("鼠标移出事件");});$("div").mouseovet(function(){alert("鼠标移出事件");});//下面的移入,移出事件与上面的区别是(不会影响子元素)$("div").mouseenter(function(){alert("鼠标移入事件");});$("div").mouseleave(function(){alert("鼠标移出事件");});

动画

$("div").show(1000);//一秒显示$("div").hide(1000);//一秒隐藏$("div").slideDown(1000);//一秒下拉显示$("div").slideUp(1000);//一秒上拉隐藏$("div").slideToggle(1000);//如果之前是隐藏就一秒下拉显示,如果之前是显示就一秒上拉隐藏$("div").fadeIn(1000);//一秒淡入$("div").fadeOut(1000);//一秒淡出$("div").fadeTo(1000,0.5);//一秒到指定透明度$("div").fadeToggle(1000);//如果之前是隐藏就一秒淡出,如果之前是显示就一秒淡出自定义动画:$("div").stop().animate({left:1000},1000,function(){alert("回调");});//在下一次触发时上一次的动画停止$("div").delay();//延迟动画$("div").finish();//停止当前动画,并删除所有队列中的动画

ajax请求:

//普通get请求<!DOCTYPE html><html>    <head>        <meta charset="UTF-8">        <title>登录验证</title>        <script src="js/jquery-3.2.1.min.js"></script>        <script>            $(function(){                $(":button").click(function(){                    var name = $(":text").val();                    var password = $(":password").val();                    $.ajax({                        type:"get",                        url:"php/doa.php?name=" + name +"&password=" + password,                        success:function(data){                            if(data == 1){                                alert("登录成功");                            }else{                                alert("用户名或密码错误!!!");                            }                        }                    });                });            });        </script>    </head>    <body>        用户名:<input type="text" id ="name"/><br>        密码:<input type="password" id="password"/><br>        <input type="button" value="登录"/>    </body></html>php:<?php   $name = $_GET["name"];   $password = $_GET["password"];   if($name == "root"){      if($password == "123456"){         echo 1;      }   }?>//post请求<!DOCTYPE html><html>    <head>        <meta charset="utf-8" />        <title>登录</title>    </head>    <script src="js/jquery-3.2.1.min.js"></script>    <script>        $(function(){            $(":button").eq(0).click(function(){                var name = $(":text").val();                var password = $(":password").val();                $.ajax({                    type:"post",                    url:"php/login.php",                    data:{username:name,password:password,mess:"1"},                    success:function(da){                        if(da == "true"){                            alert("登录成功");                        }else{                            alert("用户名或密码错误");                        }                    }                });            });            $(":button").eq(1).click(function(){                var name = $(":text").val();                var password = $(":password").val();                $.ajax({                    type:"post",                    url:"php/login.php",                    data:{username:name,password:password,mess:"0"},                    success:function(da){                        if(da == "true"){                            alert("注册成功");                        }else{                            alert("用户名重复,亲,再想一个");                        }                    }                });            });        });    </script>    <body>        用户名:<input type="text" id ="name"/><br>        密码:<input type="password" id="password"/><br>        <input type="button" value="登录"/>        <input type="button" value="注册" />    </body></html>//php<?php    $_username = $_POST["username"];    $_password = $_POST["password"];    $_mess = $_POST["mess"];    //连接数据库    $_link = new mysqli("localhost","root","123456","ajax",3306);    //设置编码    $_link->set_charset('utf8');    if($_mess == "1"){        //sql语句        $_selSql = 'select * from users where username="'.$_username.'"';        //结果集        $_res = $_link->query($_selSql);        //遍历结果集(一条)        $_row = $_res->fetch_row();        if($_row[1] === $_password){            echo "true";        }else{            echo "false";        }        $_res->free();    }else{        $_selSql = 'insert into users values("'.$_username.'","'.$_password.'")';        $_res = $_link->query($_selSql);        if($_res == 1){            echo "true";        }else{            echo "false";        }    }    //断开连接    $_link->close();?>//跨域$.ajax({                        type:"get",                        url:"http://so2.4399.com/search/lx.php?k="+txt,                 dataType:"jsonp",                       jsonp:"jsoncallback",                       success:function(data){                         console.log(data)}