前端之jQuery

 

jQuery语法操作:$("selector").action()

寻找元素(选择器与筛选器)

基本选择器:

$("*") 查找所有标签; $("#id") 查找某id标签; $(".class") 查找class标签;  
$("element") 查找某一类标签如($("p"));  $(".class,#id") 联合查找

层级选择器:

$(".outer div")  查找所有后代; $(".outer>div") 查找所有子代;  $(".outer+div") 查找相邻兄弟; $(".outer~div") 查找不相邻兄弟


//常用的就是前六个

基本筛选器:

$("li:first")  $("li:eq(2)")  $("li:even") $("li:gt(1)")
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<ul>
    <li class="tiem1">111</li>
    <li class="tiem2">222</li>
    <li class="tiem3">333</li>
    <li class="tiem4">444</li>
    <li class="tiem5">555</li>
    <li class="tiem6">666</li>
</ul>


<script src="jquery-3.2.1.js"></script>
<script>
    $("li:first").css("color","red");
    //li标签的第一行变红
    $("li:last").css("color","red");
    //li标签的最后一行变红
    $("li:eq(3)").css("color","red");
    //li标签索引为3的变红
    $("li:gt(3)").css("color","red");
    //li标签索引大于3的变红
    $("li:lt(3)").css("color","red");
    //li标签索引小于3的变红
    $("li:even").css("color","red");
    //li标签索引为偶数的变红
</script>
</body>
</html>
View Code

属性选择器:

$('[id="div1"]')  $('["viking"="sb"]')
//自定义属性

表单选择器

$("[type='text']")----->$(":text")         注意只适用于input标签  : $("input:checked")
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        *{
            margin: 0px;
        }
        .left{
            float: left;
            width: 25%;
            height: 800px;
            background-color: burlywood;
        }
        .right{
            float: left;
            width: 75%;
            height: 800px;
            background-color: wheat;
        }
        .title{
            background-color: yellow;
            text-align: center;
            line-height: 40px;
        }
        .con{
            list-style: none;
            padding-left: 80px;
            font-size: 18px;
            color: white;
        }
        .hide{
            display: none;
        }
    </style>

</head>
<body>
<div class="outer">
    <div class="left">
        <div class="item">
            <div class="title" onclick="foo(this)">菜单一</div>
            <ul class="con">
                <li>111</li>
                <li>111</li>
                <li>111</li>
                <li>111</li>
            </ul>
        </div>
        <div class="item">
            <div class="title" onclick="foo(this)">菜单二</div>
            <ul class="con hide">
                <li>222</li>
                <li>222</li>
                <li>222</li>
                <li>222</li>
            </ul>
        </div>
        <div class="item">
            <div class="title" onclick="foo(this)">菜单三</div>
            <ul class="con hide">
                <li>333</li>
                <li>333</li>
                <li>333</li>
                <li>333</li>
            </ul>
        </div>
    </div>
    <div class="right"></div>

</div>


<script src="jquery-3.2.1.js"></script>
<script>
    function foo(self) {

        $(self).next().removeClass('hide');

        $(self).parent().siblings().children('.con').addClass("hide");

    }


</script>
</body>
</html>
左侧菜单

查找筛选器

$("div").children(".test")    
//查找div标签的子代中class="test"的标签

$("div").find(".test")  
//查找div标签的后代中class="test"的标签
                               
$(".test").next()   
//查找class="test"的下一个标签(相邻)                    
$(".test").nextAll()  
//查找class="test"的下面所有的标签       

$(".test").nextUntil(可填下标值)
//查找class="test"的下面所有的标签,如果填值则取到相应标签

$("div").prev()  
$("div").prevAll()  
$("div").prevUntil()   
//同next一样,只不过是往上取                        

$(".test").parent()  
$(".test").parents()  
$(".test").parentUntil() 
//查找标签父类

$("div").siblings()
//查找除自己外的其他相邻标签

元素操作(属性,css,文档处理)

--------------------------属性
$("").attr();
$("").removeAttr();
$("").prop();
$("").removeProp();
--------------------------CSS类
$("").addClass(class|fn)
$("").removeClass([class|fn])
--------------------------HTML代码/文本/值
$("").html([val|fn])
$("").text([val|fn])
$("").val([val|fn|arr])
---------------------------
$("").css("color","red")
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<input type="text" value="" name="username">
<p>first P</p>
<p>second P</p>

<script src="jquery-3.2.1.js"></script>
<script>
//    console.log($("p").first().text());
    //取出第一个p标签的文本值,console.log()在控制台查看
//    $("p").first().text('hello')
    //text()括号里有值就是赋值
//    console.log($("p").last().html());
    //取出最后一个p标签的文本值,看似与text一样
//    console.log($("p").last().html('hello'));
    //赋值
//    console.log($("p").last().html('<h1>hello</h1>'));
    //与text的区别就是在于html可以创建一个标签,而text则是纯文本
//    console.log($("input").val());
    //取出input框中输入的值
//    console.log($("input").val('123'));
    //给input框中赋值

</script>
</body>
</html>
文本操作
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<input type="text" value="" name="username">
<p class="p1">first P</p>
<p class="p2">second P</p>

<script src="jquery-3.2.1.js"></script>
<script>
    $(".p1").addClass("P1");
    //添加一个类名
    $(".p2").removeClass("p2");
    //移除一个类名
    $(".p1").css("color","red");
    //对标签进行css操作
</script>
</body>
</html>
css操作
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<p id="p1">first P</p>
<p class="c1" test="jquery">second P</p>
<input type="text" value="" name="username">
<input type="checkbox" checked="checked">


<script src="jquery-3.2.1.js"></script>
<script>
//    console.log($("p").last().prop("class"));
//    console.log($("p").prop("id"));
    //取出标签中的属性
//    console.log($("p").last().attr("test","123"));
    //取出自定义属性名称,逗号分隔属于赋值

//    console.log($("[type='checkbox']").prop("checked"));
    //查看checked是否选中
//    console.log($(":checkbox")).prop("checked"));   //简写形式 只适用于input标签

//    console.log($("p").last().removeAttr("class"));
//    console.log($("p").first().removeAttr("id"));
    //移除属性

</script>
</body>
</html>
属性操作

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<ul>
    <li>111</li>
    <li>222</li>
    <li>333</li>
    <li>444</li>
    <li>555</li>
    <li>666</li>
</ul>


<script src="jquery-3.2.1.js"></script>
<script>

    //JQ循环方式一
//    var l=[11];
//    var list=[11,22,'hello',l];
//
//    $.each(list,function (i,j) {
//        console.log(i);//索引值
//        console.log(j);//索引值对应的值
//    })

//    dict={"name":"jquery","version":1.3};
//    $.each(dict,function (k,v) {
//        console.log(k);
//        console.log(v);
//    });//循环字典

    //JQ循环方式二(循环标签)
    $("ul li").each(function () {
        console.log($(this).text());//循环取出标签中的文本
    });
</script>
</body>
</html>
jQuery的两种循环方式
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<button>全选</button>
<button>取消</button>
<button>反选</button>
<hr>
<table border="1px" class="Form">
    <tr>
        <td><input type="checkbox"></td>
        <td>1111</td>
        <td>1111</td>
        <td>1111</td>
    </tr>
    <tr>
        <td><input type="checkbox"></td>
        <td>1111</td>
        <td>1111</td>
        <td>1111</td>
    </tr>
    <tr>
        <td><input type="checkbox"></td>
        <td>1111</td>
        <td>1111</td>
        <td>1111</td>
    </tr>
    <tr>
        <td><input type="checkbox"></td>
        <td>1111</td>
        <td>1111</td>
        <td>1111</td>
    </tr>
</table>
<script src="jquery-3.2.1.js"></script>
<script>
    //标签对象.事件(函数)
    $("button").click(function () {
        if ($(this).text()=="全选"){
            $(".Form input").prop("checked",true);
        }

        else if ($(this).text()=="取消"){
            $(".Form input").prop("checked",false);
        }

        else if ($(this).text()=="反选"){
            $(".Form input").each(function () {
                if ($(this).prop("checked")){
                    $(this).prop("checked",false);
                }
                else{
                    $(this).prop("checked",true);
                }
            })
        }
    })

</script>

</body>
</html>
表格全反选
节点操作
//
创建一个标签对象 $("<p>") //内部插入(向父级添加子级) var ele=$("<p>"); ele.text("hello"); //标签创建成功但是并没有值使用.text进行文本赋值 $("body").append(ele) //外部插入(插在兄弟后面) var ele=$("<p>"); ele.text("hello"); $("body").append(ele); //替换 var ele=$("<img>"); ele.attr("src","timg.jpg"); $("h1").replaceWith(ele); //替换 //删除与清空 $(".outer").empty();//清空 标签数据清空 但是标签还在 $(".outer").remove(); //删除 标签都不存在 //复制 var ele=$("h1").clone();//复制 $("h1").after(ele);
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<div class="box">
    <div class="item">
        <input type="button" value="+">
        <input type="text">
    </div>
</div>


<script src="jquery-3.2.1.js"></script>
<script>
    $("[type='button']").click(function () {
        var ele=$(this).parent().clone();
        ele.children().first().val("-").attr("onclick","removed(this)");
        $(".box").append(ele);
    });
    function removed(self) {
            $(self).parent().remove();
    }

</script>
</body>
</html>
复制样式条

css操作

CSS
        $("").css(name|pro|[,val|fn])
    位置
        $("").offset([coordinates])
        $("").position()
        $("").scrollTop([val])
        $("").scrollLeft([val])
    尺寸
        $("").height([val|fn])   //盒子的高度
        $("").width([val|fn])   //盒子的宽度
        $("").innerHeight()     //盒子加上padding的高度
        $("").innerWidth()
        $("").outerHeight([soptions])   //盒子加上border的高度(括号里填true)则为盒子加上margin的高度
        $("").outerWidth([options])
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        *{
            margin: 0px;
        }
        .c1{
            width: 200px;
            height: 200px;
            background-color: rebeccapurple;
        }

        .c2{
            width: 200px;
            height: 200px;
            background-color: red;
        }
    </style>
</head>
<body>
<div class="c1"></div>
<div class="c2"></div>

<button>change</button>

<p id="p1"></p>
<script src="jquery-3.2.1.js"></script>
<script>
    var offset=$(".c2").offset();

    $("#p1").text("c2--------------left:"+offset.left+"top"+offset.top);//查看坐标

    $("button").click(function () {
        $(".c2").offset({left:200,top:400});//自定义坐标
    });

</script>
</body>
</html>
$("").offset([coordinates])
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        *{
            margin: 0px;
        }
        .c1{
            width: 200px;
            height: 200px;
            background-color: rebeccapurple;
        }

        .c2{
            width: 200px;
            height: 200px;
            background-color: red;
        }
        .c2_father{
            position: relative;

        }
    </style>
</head>
<body>
<div class="c1"></div>
<div class="c2_father">

    <div class="c2"></div><!--测试可以将c2_father盒子去掉在进行测试查看p标签值 -->
</div>


<button>change</button>

<p id="p1"></p>
<script src="jquery-3.2.1.js"></script>
<script>
    var position=$(".c2").position();

    $("#p1").text("c2--------------left:"+position.left+"top"+position.top);//查看坐标
    //按照父级定位

</script>
</body>
</html>
$("").position()
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .c1{
            width: 100%;
            height: 5000px;
            background-color:gainsboro;
        }

        .top{
            width:50px;
            height: 30px;
            background-color: saddlebrown;
            text-align: center;
            line-height: 30px;
            position: fixed;
            color: white;
            bottom: 20px;
            right: 20px;
            display: none;
        }
    </style>
</head>
<body>

<div class="c1"></div>
<div class="top">top</div>

<script src="jquery-3.2.1.js"></script>
<script>
    $(".top").click(function () {

        $(window).scrollTop(0)
    });
    $(window).scroll(function () {
        console.log($(window).scrollTop());
        if ($(window).scrollTop()>200){
            $(".top").css("display","block");//大于200显示
        }
        else {
            $(".top").css("display","none"); //小于200隐藏
        }
    });

</script>
</body>
</html>
返回顶部

 事件

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

<ul>
    <li>111</li>
    <li>111</li>
    <li>111</li>
</ul>
<button class="add">add</button> <button>off</button>
<script src="jquery-3.2.1.js"></script> <script> // $("ul li").click(function () { // alert(123); //简单方法事件绑定 // }); //------------------------------------------------------------------------- // $("ul li").on("click",function () { // alert(789); //常规方法时间绑定 // }); //-------------------------------------------------------------------------- // $("button").click(function () { // $("ul li").off(); //解除事件绑定(解开上面注释查看效果) // }); //-------------------------------------------------------------------------- // $("ul").on("click","li",function () { // alert(777); //解开我 // }); $(".add").click(function () { $("ul").append("<li>707</li>"); //新添加的li标签并不能触发alter。解决方法解开上面三行注释 });//这就是事件委派

</script> </body> </html>

jQuery代码执行效果为从上往下执行,写在head中效果无法加载出来。但是如果想要房子上面也是没问题需要绑定一个页面加载完的事件

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="jquery-3.2.1.js"></script>
    <script>
        $(document).ready(function () { //等待页面加载完毕
            //代码块
        });
        
        //简写形式
        $(function () {
            //代码块
        });
    </script>
</head>
<body></body>
</html>

动画效果

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

<hr>
<button onclick="show()">显示</button>
<button onclick="hide()">隐藏</button>
<button onclick="toggle()">切换</button>

<script src="jquery-3.2.1.js"></script>
<script>
    function show() {
        $("p").show();
    }
    function hide() {
        $("p").hide(1000); //可以添延迟时间1000=1秒
    }
    function toggle() {
        $("p").toggle();
    }
</script>
</body>
</html>
显示与隐藏
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<div style="line-height: 50px;background-color: greenyellow;text-align: center">hello world</div>

<hr>
<button onclick="slidedown()">slideDown</button>
<button onclick="slideup()">slideUp</button>
<button onclick="slidetoggle()">slideToggle</button>

<script src="jquery-3.2.1.js"></script>
<script>
    function slidedown() {
        $("div").slideDown();
    }
    function slideup() {
        $("div").slideUp(1000); //可以添延迟时间1000=1秒
    }
    function slidetoggle() {
        $("div").slideToggle();
    }
</script>
</body>
</html>
滑动
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<div style="line-height: 50px;background-color: greenyellow;text-align: center">hello world</div>

<hr>
<button onclick="fadein()">fadeIn</button>
<button onclick="fadeout()">fadeOut</button>
<button onclick="fadetoggle()">fadeToggle</button>
<button onclick="fadeto()">fadeTo</button>

<script src="jquery-3.2.1.js"></script>
<script>
    function fadein() {
        $("div").fadeIn(1000);
    }
    function fadeout() {
        $("div").fadeOut(1000); //可以添延迟时间1000=1秒
    }
    function fadetoggle() {
        $("div").fadeToggle(1000);
    }
    function fadeto() {
        $("div").fadeTo(1000,0.6); //0.6为透明度,从1到0 期间是0.9 0.8 ...0.1 0
    }
</script>
</body>
</html>
淡入淡出
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<div style="line-height: 50px;background-color: greenyellow;text-align: center">hello world</div>

<hr>
<button onclick="slidedown()">slideDown</button>
<button onclick="slideup()">slideUp</button>
<button onclick="slidetoggle()">slideToggle</button>

<script src="jquery-3.2.1.js"></script>
<script>
    function slidedown() {
        $("div").slideDown(1000,function () { //在函数中添加一个函数为回调函数
                    alert(123); //当上述动作执行完后会自动触发这个函数
        });
    }
    function slideup() {
        $("div").slideUp(1000); //可以添延迟时间1000=1秒
    }
    function slidetoggle() {
        $("div").slideToggle();
    }
</script>
</body>
</html>
回调函数

扩展方法(插件机制)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<!--扩展方式二代码-->
<input type="checkbox">
<input type="checkbox">
<input type="checkbox">
<input type="checkbox">



<script src="jquery-3.2.1.js"></script>
<script>
    //扩展方式一
//    $.extend({
//        test:function () { //无参
//            alert("自定义test方法")
//        }
//    });
//    $.test()

//    $.extend({
//        maxs:function (a,b) {   //有参
//            return  a>b ? a:b;
//        }
//    });
//    console.log($.maxs(1,2))

    //扩展方式二
    $.fn.extend({
        check:function () {
            $(this).prop("checked",true);//选中所有checkbox标签
        }
    });

    $("input").check()

</script>
</body>
</html>

定时器

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


<script>
    function foo() {
        console.log("ok")
    }
    setInterval(foo,1000);//1秒钟执行一次foo函数
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<input type="text" onfocus="start()"> <!--获取焦点 -->

<script>

    function data() {
        var now=new Date().toLocaleString();
        var ele=document.getElementsByTagName("input")[0];//js找标签,找到一个数组[0]为第一个
        ele.value=now; //js下直接对标签属性进行赋值
    }

    function start() {
        data();     //先执行一个这个函数,然后在开始定时,不然点进去会卡一秒
        setInterval(data,1000)
    }

</script>
</body>
</html>
定义定时器
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<input type="text" onfocus="start()"> <!--获取焦点 -->
<button class="end" onclick="end()">end</button>
<script>
    var ID;//定义局部变量end函数无法执行,所以要定义全局变量
    function data() {
        var now=new Date().toLocaleString();
        var ele=document.getElementsByTagName("input")[0];
        ele.value=now;
    }

    function start() {
        data();
        ID=setInterval(data,1000); //每一个定时器都有一个唯一的一个ID号
    }
    function end() {
        clearInterval(ID); //清除ID
    }
</script>
</body>
</html>
清除定时器

注册验证

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form action="">
    <p>用户名:<input type="text" name="" class="con" custom="用户名"></p>
    <p>密&nbsp;&nbsp;&nbsp;码:<input type="password" name="" class="con" custom="密码"></p>
    <p><input type="submit" value="提交"></p>
</form>


<script src="jquery-3.2.1.js"></script>
<script>
    $("form :submit").click(function () {//为submit绑定事件
        var flag=true; //设置标志位
        $(".con").each(function () {     //循环判断是否为空
            $(this).next("span").remove();// 不写这个可以试着看看
            if (!$(this).val().trim()){

                var ele=$("<span>");    //创建新标签

                var custom=$(this).attr("custom"); //取出自定义属性,做字符串拼接
                ele.text(custom+"不能为空!");
                $(this).after(ele);
                flag=false;     //当为空的时候不提交
            }
        });
            return flag;
    });


</script>
</body>
</html>
实例注册验证

 

posted @ 2017-08-15 14:29  沧澜猛兽  阅读(210)  评论(0)    收藏  举报