首页 > 技术文章 > jquery基础学习

solaris-wwf 2019-10-09 12:50 原文

1.jquery
    1 WHAT:轻量级功能强大的javascript
    2.选择器
        $是构造函数,就是jquery$('body')返回的是一个伪数组,不是一个数组,是一个jquery的一个实例,可以使用单引号和双引号,但是htmlbody只能用单引号,否则无法选中。
            var b = $("body");b instanceof Array;//false
            var b = $("body");b instanceof jQuery;

 

        jquery对象的方法是定义在jquery构造函数的原型之上的,
             jquery.prototype.addClass(); 
        也有直接构造在jquery上的方法
             jquery.ajax(); 
    3.属性
        html,val,prop,attr
            html对应innerHtml,val对应value,
                 $("input").keyup = function(){var v=this.val();this.val(v + "px");} 
        
            prop对应property指的是树上选取下来的节点它对象的属性,attr对应attribute指的是元素标签内的属性,通常情况下他们的值是一一对应的。比如attrclassprop上的className,他们的名字虽然不同,但他们的值是相等的,还有id等。某些属性是不同的,checkbox的属性check,attr上的check属性只是checkbox的默认值,而prop上的check表示是否选中。
                $("input[type=checkbox]").change(function(){
                    console.log($(this).attr("checked"));
                    console.log($(this).prop("checked"));});

 

        addClass/removeClass/hasClass/toggleClass
            toggleClass切换类
                $("div").click(function(){
                    $(this).toggleClass("slide");//判断是否有slide类,如果有就删除,
                    $(this).toggleClass("stop");//如果没有这个类则把这个类添加上去
                })

 

        练习
    <input type="checkbox" value="nan" name="p2" id="" checked><input type="checkbox" name="p2" id="" value="nv">
    <table>
        <thead><tr><th><input type="checkbox"></th></tr></thead>
        <tbody><tr><th><input type="checkbox"></th>
            <th><input type="checkbox"></th>
            <th><input type="checkbox"></th></tr></tbody>
    </table>
                $("thead input").change(function(){
                var isChecked = $(this).prop("checked");
                $("tbody input").prop("checked",isChecked);
            })
            $("tbody input").change(function(){
                var btnLength = $("tbody input").length;
                var checkedCount = $("tbody input:checked").length;
                var isAllChecked = btnLength === checkedCount;
                $("thead input").prop("checked",isAllChecked);
            })

 

    4.动画
        show/hide
             $("div:last").show(3000);//3秒后显示出来,透明度宽高都改变 
        fadeIn/fadeOut
             $("button:eq(0)").fadeIn(3000);//透明度效果。 
        slideUp/slideDown
             $("button:first").slideUp();//向下拉出效果 
        animate/stop
            $("div").animate({height:200,width:200},5000);
            $("div").animate({height:200}).animate({width:200});//先改变高,在改变宽,
            原理:先创建一个队列,并且没调用一次函数就调用一次动画事件,当一个动画事件结束之后,才会开始另一个事件
            $("button:last").click(function(){
                $("div").stop();//停止当前的事件,如果有后续的事件并不停止。如果传入参数true,则停止所有动画。
            })

 

2.jquery进阶
    1.遍历
        children,parent,parents,find,next,pref,siblings
        1.
    <div id="container">
        <ul class="list">
            <li class="item">
                <p>1</p>
            </li>
            <li class="item">
                <p>2</p>
            </li>
            <li class="item">
                <p>3</p>
            </li>
            <li class="item">
                <p>4</p>
            </li>
            <li class="item">
                <p>5</p>
            </li>
        </ul>
    </div>
     $li = $('li:eq(1)');//所有li的第二个li。得到一个jquery对象,一个伪数组
            $li.children().css('background','red');
            $li.parent().css('color','yellow');
            $li.parents('div#container').append('<h2>添加新元素到最后</h2>');//parents()表示选中了父元素,以及父元素的父元素,包含了所有父元素直到html。
            $('#container').find('p').css({bacground:'#333',color:'#fff'});//children只能查找子元素,find可以查找父元素下的所有的元素,
            next(),pref();//表示后一个同级元素和前一个同级元素。
            $li.siblings().css({fontweight:'bold'});//获取同级的所有元素。

 

    2.dom操作
    3.ajax
        1.$.ajax
            1.get
                $.ajax({
                    type:'get',
                    url:'../js/person.json',
                    data:{
                        name:'sarah'
                    },//如果我们想传递参数,可以加入data,他会自动将DATA连接到url上,会出现在url?后面发送给服务器
                    success:function(resp){
                        console.log(resp.hobby);
                    },
                    error:function(){
                            console.log('error');
                    }
                })

 

            2.post
                get改成post即可
        我们依然要注意回调地狱问题,如果我们有很多ajax,且它们的前后顺序有依赖关系,且同步的发送。jqueryajax添加了一个方法,类似于es6中新添加的promise方法。
            $.ajax({
                type:'get',
                url:'../p1.ap'
            }).done(function(){//如果成功,执行。
                return $.ajax({url:'../p2.ap'})
            }).fail(function(){//如果失败,执行。
 

            })

 

        2.jsonp
            jquery中把jsonp封装到了ajax中,但是jonspajax是没有什么联系的,他们都是取得数据的方式,但是他们的原理是不相同的
                $.ajax({
                type:'get',
                dataType:'jsonp',
                jsonp:'cb',//jsonp的方法名称,jquery会自动生成cb=的方法名称。
                data:{wd:'jsonp'},//jsonp要传入的参数wd,这里相当于要baidu搜素的关键词
                url:'https://www.baidu.com/sugrec?&prod=pc'
            }).done(function(resp){
                    console.log(resp.g);
            })

 

        3.$.get/$.post
    4.事件
        原生中的事件处理可以使用DOM流的事件处理程序,这种方式只能在冒泡阶段处理事件,且不能重复绑定,第二种方式是addEventLisener,可以重复绑定,且可以在冒泡阶段,jquery处理事件的时候使用的是一个函数on()
            原生流中this指针指向的是流经的那个元素,而jquery中也是一样的,但要注意这是原生的DOM节点,所以要加上$
            $('li').on('mouseover',function(){$(this).css('background','#333');})    

 

        jquery还支持事件列式操作
            $('li').on('mouseover',function(){$(this).css('background','#333');}).on('mouseout',function(){$(this).css('background','#fff');})

 

        与某个元素解绑,可以使用off()方法,off可以传递两个参数,1,event type,事件的名称。2.callback name  回调函数,如果之前使用的是匿名函数,也可以使用事件代替。
             $('li:eq(3)').off('mouseout'); 
            如果创建了一个新元素,则这个事件需要重新绑定,或者事件代理
             $('<li>newLi</li>').appendto('ul'); 
        事件代理
            加入第二个参数,是真正代理的元素选择器。li:even表示只有奇数的li被代理事件。
            $('ul').on('mouseover','li',function(){
                $(this).css('background','#333');
            })
            $('<li>newLi</li>').appendto('ul');

 

    节点的操作练习
        append,appendto,prepend,prependto,after,insertafter
            var $el = $('<div>new element</div>')
            $('body').append($el);//或者:$el.appendto('body');
            $('ul').prepend($el);//在ul中的子元素第一个插入一个元素。或者:$el.prependto('ul');
            $('ul li:eq(1)').after('<li>1.5</li>');//在第2个li的后面插入一个li;或者:$('<li>1.5</li>').insertafter('ul li:eq(2)')
            $('button').click(function(){
                $('ul li:eq(1)').remove();//删除第二个li。
                $('ul li:eq(2)').empty();//清空第三个li里面的内容,相当于innerHtml;
            })

 

    自定义插件
        有时候,很多代码需要重复利用的,我们自己做一些插件的时候,使用起来就会非常的方便。
        1.jquery的插件是定义在jQuery.fn上的
        2.命名冲突的解决。
            可以使用一个立即执行函数,在函数中传递此实参jQuery,并且在形参中用$符号来接收实参,这样的话,即使我们的$被占用,在这个函数中,我们的$依然是指向jQuery的,这样我们就可以避免命名冲突.
            
        3.循环jQuery对象中的每个元素。
        4.在函数中,将jQuery对象返回。
            1.闭包
            2.this.each
            3.return this
  (function($){//立即执行函数(function(){})(jQuery)
  $.fn.extend({//用extend来进行功能的扩展。
  randomColor:function(){//方法名称

 

                    
                        this.each(function(index,el){用each方法来遍历jQuery对象。index表示当前这个元素在伪数组中的索引,el表示这个元素本身,el===this,this已经不指向jQuery对象了,而是指向了jQuery对象中的每一个元素,因为在js中,this会根据函数的不同指向不同的对象,因为this指向el,所以el可以不写})
                        function random(){
                            var r = Math.floor(Math.random()*256);//选取0-255之间,Math.random含0不含1.
                            var g = Math.floor(Math.random()*256);
                            var b = Math.floor(Math.random()*256);
                            return 'rab('+ r + ',' + g + ',' + b + ')';
                        }
                        this.each(function(index){//遍历伪数组
                            $this.css('backgroundColor',random());
                        })
                        return this;
                    }
                })
            })(jQuery);//jQuery实参
            $('div').randomColor();//调用函数的方法。

 

    放大镜插件的实现
        命名,jquery.magnifier.jsjquery.magnifier.css  文件,可以将jscss引入。
    
        .magnifier .left{height: 176px;width: 128px;float: left;position: relative;}
        .magnifier .right{height: 200px;width: 200px;background: url("../img/1.jpg");margin-left:150px;display: none}
        .magnifier .left img{height: 176px;width: 128px;display: block;}
        .magnifier .left .mask{height: 100%;width: 100%;top: 0;left: 0;position:absolute ;}
        .magnifier .left .float{height: 50px;width: 50px;display: none;background: #333;opacity: .5;position: absolute;left: 0;top: 0;}
    <div class="magnifier">
        <div class="left">
            <img src="../img/1s.jpg" alt="">
            <div class="float"></div><!-- 作用是光标移动时,跟着光标走的小div -->
            <div class="mask"></div><!-- 保护我们的float不会闪烁的一个最基本的div,它是一个遮罩层。 -->
        </div>
        <div class="right"></div><!-- 装的页面上的大图片, -->
    </div>
(function($){
    $.fn.extend({
        magnifier:function(){//方法名称
            this.each(function(){//将伪数组进行遍历。
                    var that = this;
                $('.left',this).mousemove(function(e){
                    var evt = e || event ;//封装隐藏参数,兼容ie6
                    var x = evt.offsetX;//获取鼠标距离整个容器这个div中的x和y值
                    var y = evt.offsetY;
                    var float = $('.float',this);//this这个float在当前.left元素下
                    x = x - float.width() / 2;
                    y = y - float.height() / 2;
                    if(x < 0){
                        x = 0;//x设定固定值,为了不让浮动窗口跳出整个窗口。
                    }
                    if( x > $(this).width() - float.width()){//现在的this被定义成了.left这个div,判定条件如果x大于了整个宽度减去浮动窗口的宽度
                        x = $(this).width() - float.width();//则x设定固定值,为了不让浮动窗口跳出整个窗口。
                    }
                    if(y < 0){
                        y = 0;
                    }
                    if( y > $(this).height() - float.height()){
                        y = $(this).height() - float.height();
                    }
                    float.css({left:x,top:y});//让float这个图层始终保持在鼠标中间
                    $('.right',that).css({backgroundPosition:x * -4 + 'px '+ y * -4 + 'px'});//定义了that在整个.magnifier元素下,因为大图是小图的4倍,'px '后面记得留一个空格,要不然无法运行。
                    $('.right,.left .float',that).show();//鼠标一进去的时候,显示float和right类的div
                }).mouseover(function(){
 

                }).mouseout(function(){
                    $('.right,.left .float',that).hide();//鼠标移出的时候,不显示float和right类的div
                });//this监听.left这个div。
            })
        }
    })
})(jQuery)
   $('.magnifier').magnifier();

 

推荐阅读