zoukankan      html  css  js  c++  java
  • 锋利的jQuery

    今天总要找点东西学习,其实有很多东西要记录,慢慢写,今天看书吧,这几天把这本书看完,这里记一些要点

    从头开始记吧

    第一章 认识jQuery

    $就是jQuery的简写

    $(function(){}) 就是 $(document).ready(function(){})的简写

    与window.onload相比有三点(执行时机、编写个数、有无简写)

    DOM---文档对象模型,BOM---浏览器对象模型

    第二章 jQuery选择器

    和css选择器相同

    基本选择器:

    <1> $("#test")  id选择器

    <2> $(".test")  类选择器

    <3> $("p") 标签选择器

    <4>$("*") 选择所有元素

    <5>$("div,span,.myclass") 组合------可组合,这个很实用

    层次选择器:

    <1>$("div span")  选择div中  span后代元素

    <2>$(“div >span”) 选择div中span的子元素

    <3>$(“.one + div”)选one的下一个div元素————相当于$(“.one”).next("div")       //同辈的下一个元素

    <4>$("#two ~ div") 选id为two的后面所有<div>兄弟元素————相当于$(“#two”).nextAll("div");     //不包含#two

    过滤选择器:

    <1>$(" div:first") 所有div元素中第一个div
    <2>$(" div:last") 所有div元素中最后一个div
    <3>$(" input:not(.myclass)") 不是 class为myclass 的<input>元素
    <4>$(" input:even") 索引为偶数的input                                            //可以做隔行变色
    <5>$(" input:odd")索引为奇数的input
    <6>$("input:eq(1)") 索引为1的input——————index从0开始            //$('div:eq(1)').css('backgroundColor','red');     单一选择
    <7>$("input:gt(1)") 索引大于1的input              从0开始,不包含1        //$('#one a:gt(0)').css('color','red');         向下数       
    <8>$("input :lt(1)") 索引小于1的input              从0开始                   //向上数
    <9>$(":header") 所有的<h1> <h2> <h3>......
    <10>$("div:animated") 正在执行动画的<div>
    <11>$("div:contains('我')") 含有文本‘我’的div
    <12>$("div:empty") 空的div
    <13>$(" div :has(p)") 含有<p>的<div>                                         //$('#one a:has(span)').css('color','red');    包含span的a                       
    <14>$("div:parent") 含有子元素的<div>
    <15> $(":hidden") 所有不可见元素
    <16>$("div:visible") 所有的可见的<div>
    <17>$(" div[id]") 拥有id属性的<div>
    <18>$(" div[title=test]") title为test的<div>
    <19> $ ("div [title!=test]") title不为test的<div>
    <20> $(" div[title^=test]") title以“test”开头的div
    <21>$ ("div [title$=test]") title以“test”结束的div
    <22>$(" div[title*=test]") title含有test的div
    <23>$("div[id][title$=test]") 组合多条件选择
    <24>:nth-child(index/even/odd/equation) ————————index从1开始
    <25>:first-child
    <26>:last-child
    <27> :only-child
    <28> $("#form1 :enabled") id为“form1”的表单内所有可用的元素
    <29>$("#form2:disable")
    <30>$("input:checked") 所有被选中的<input>元素
    <31>$("select:selected") 所有被选中的<select>元素
    <32>$(":input") 所有<input> <textarea><select><button> 元素
    <33>$(":text") 所有单行文本框
    <34>$(":password") 所有密码框
    <35>$(":radio") 所有单选框
    <36>$(":checkbox") 所有复选框
    <37>$(":submit") 所有的提交按钮
    <38>$(":image") 所有图像按钮
    <39>$(":reset") 所有重置按钮
    <40>$(":button") 所有按钮
    <41>$(":file") 所有上传域
    <42>$(":hidden") 所有不可见元素

    有些常用,有些不常用,这里做个记录

    为了练习写了个小例子,全选,全不选

    <input type="button" value='quanxuan'/>
    <input type="button" value='quanbuxuan'/>
    <input type="checkbox" />
    <input type="checkbox" checked='checked'/>
    <input type="checkbox" />
    <script>
    $('input[value=quanxuan]').click(function(){
        $('input:gt(1)').prop('checked',true)
    })
    $('input[value=quanbuxuan]').click(function(){
        $('input:gt(1)').prop('checked',false)
    })
    </script>

    当然这本书开篇就讲了,jQuery很大的优势是可以链式,所以可以写成这样

    $('input[value=quanxuan]').click(function(){
        $('input:gt(1)').prop('checked',true)
    }).next().click(function(){
        $('input:gt(1)').prop('checked',false)
    })

    第三章jQuery中的DOM操作

    0、插入节点

      <1>append()  内部追加内容

      <2>appendTo()   append()的反操作

      <3>prepend()   内部前置内容

      <4>prependTo()    prepend()的反操作

      <5>after()         外部追加内容

      <6>insertAfter()   after的反操作

      <7>before()   外部前置内容

      <8>insertBefore()    before的反操作

     1、删除节点

    $('ul li:eq(1)').remove();                //获取第二个<li>元素节点后,将他从网页中删除

    $('ul li').remove('li[title!=菠萝]');                //可以做选择性的删除

    empty()    清空节点内容

    2、复制节点

     clone()                                          //$('ul li').clone().appendTo('ul');                //复制li,并追加到ul中   复制的同时,如果clone(true),传递了true,就复制了他绑定的事件(默认是不复制事件的)

     3、替换节点

    replaceWith()和replaceAll()             //$('p').replaceWith("<a href='#'>我是忍者</a>")   功能一样,replaceWith()相当于append(),replaceAll()相当于appendTo();

    4、包裹节点

    wrap()         //$('.one').wrap("<b></b>")       被<b></b>包裹起来分别包裹

    wrapAll()     //$('.one').wrap("<b></b>")       被<b></b>包裹起来一起包裹

    wrapInner()    //$('.one').wrap("<b></b>")       被<b></b>包裹起来包裹文字

    属性操作

    获取属性、设置属性、删除属性  attr()和removeAttr

    追加移除class----addClass()和removeClass()

    切换class----toggleClass()     // $('p').toggleClass('another')

    判断元素中是否还有某class---$('span').hasClass('bca');  返回布尔值   等价于$('span').is('bca');   他内部本身就是调用is执行的

    遍历节点

    【1】children() 取子元素 (不包括后代元素)

    【2】next()    取后面紧邻的同辈元素

    【3】prev()   取前面紧邻的同辈元素

    【4】siblings() 取前后所有同辈元素

    【5】closet()  取最近的匹配元素

    css-DOM操作

    css()、height()、width()     单位默认px

    offset()    //获取元素在当前视窗的相对偏移  有两个属性 left、top            $('p').offset().top   真的是视窗

     position()    //$('.bca').position().top   //获取元素相对于最近的一个position样式属性设置为relative或者absolute的祖父节点的相对偏移,也有top和left两个值

    scrollTop()和scrollLeft()方法   //获取元素的滚动条距顶端的距离和距左侧的距离     //可以指定一个参数,控制元素的滚动条滚动到指定位置   例:   $('p').scrolTop(300);     元素的滚动条,和offset()有区别

    例子:

    //超链接提示
    1、移入超链接创建一个元素,他的内容为title属性的值
    2、将创建的元素追加到文档中
    3、为他设置x坐标和y坐标,使它显示在鼠标位置的旁边
    4、当鼠标划出链接,移除div

    $("a[title='我是title']").mouseover(function(e){
        var div="<div id='sd'>"+this.title+"</div>";   
        $('body').append(div);
        $("#sd").css({
            "position":"absolute",
            "top":e.pageY+'px',
            "left":e.pageX+'px'
        }).show("fast")
        }).mouseout(function(){
            $("#sd").remove();   // 移除
        })
        此处有两个问题,一个问题是1、当鼠标滑过时title也会显示出来。2、提示例鼠标太近。解决后代码如下
    var x=10;
    var y=20;
    $("a[title='我是title']").mouseover(function(e){
        this.myTitle=this.title;
        this.title='';
        var div="<div id='sd'>"+this.myTitle+"</div>";   
        $('body').append(div);
        $("#sd").css({
            "position":"absolute",
            "top":(e.pageY+y)+'px',
            "left":(e.pageX+x)+'px'
        }).show("fast");
        }).mouseout(function(){
            this.title=this.myTitle;
            $("#sd").remove();   // 移除
        })

    先把this.title给 this.myTitle 后,把this.title=""; 然后鼠标移除再把this.myTitle的值给this.title

    第四章jQuery中的事件和动画

    hover()  鼠标移入移出

    toggle()  在元素的click事件中绑定两个或两个以上的函数,它可以实现元素的隐藏与显示的切换

    事件冒泡

    停止事件冒泡

    $("p").click(function(event){
        event.stopPropagation();    // do something
      });  

    阻止事件默认行为

    $("p").click(function(event){
        event.preventDefault();    // 可阻止表单提交   
      });  

    如果行同时阻止默认行为以及事件冒泡,可直接返回false,这是一种简写

    return false;

    另外jQuery不支持事件捕获

    事件对象属性

    1、event.type      

    $("a").click(function(event){
        alert(event.type);
        return false;     //阻止链接跳转   click
    })

    2、event.stopPropagation();  阻止冒泡

    3、event.preventDefault();    阻止默认行为

    4、event.target();    返回触发元素

    5、event.pageX 和 event.pageY     获取光标相对于页面的x坐标和y坐标

    6、event.which   鼠标事件中获取的左中右键,在键盘事件中获取键盘键值

    $(document).mousedown(function(e){
        alert(e.which);                        //鼠标事件分别返回1,2,3
    })

      $(document).keyup(function(e){
        alert(e.which);             //键盘事件,返回键值
      })

    7、event.metaKey     针对不同浏览器对ctrl按键解释不同,jQuery也进行了封装,并规定了event.metaKey为键盘事件获取ctrl按键 

     动画

    show()和hide()里面的数字单位是毫秒fast、normal、slow 分别是0.6s、0.4s、0.2s  //执行时会同时增加/减少“内容”的高度、宽度和不透明度

    fadeIn()和fadeOut    和show()、hide()不同的是他们只是改变元素的不透明度

    sildeUp()和slideDown()    只会改变元素的高度,如果设置了display:none;当调用slideDown的时候,元素将由上至下延伸显示

    自定义动画animate  

    如果让动画动起来在前面加上 +=或者-=

    $(function(){
      $("p").click(function(){
        $(this).animate({left:"+=500px"},300)     //在当前位置累加500px
        })
    })

    动画回调函数

    $("p").click(function(){
        $(this).animate({left:"400px",height:"200px",opacity:"1"},300)
               .animate({top:"200px","200px"},300,function(){
                   $(this).css("border","5px solid blue")
               })
    })

    停止动画   stop()  方法

    判断是否处于动画状态

    if(!$(element).is(":animate")){   //判断元素是否处于动画状态
        .....
    }

    延迟动画  delay()

    $(this).animate({left:"400px",height:"200px"},3000)
           .delay(1000)
           .animate({top:"200px","200px"},3000)
           .delay(2000)
           .fadeOut("slow"); 

    其他动画

    toggle(speed,[callback])

    slideToggle(speed,[easing],[callback])

    fadeTo(speed,opacity,[callback])

    fadeToggle(speed,[easing],[callback])

    第五章 jQuery对表单、表格的操作及更多应用

    focus()和blur()   获取焦点失去焦点

    第六章 jQuery与Ajax的应用

     load()    方法能远程载入HTML代码并插入DOM中

    $(function(){
        $("#send").click(function(){
            $("#resText").load("test.html")
        })
    })                                 //当点击后,test.html 页面的HTML内容会被加载并插入主页面<div id="resText"></div>的元素中

    如果只需要加载test.html页面中class 为 "para" 的内容

    $("#resText").load("test.html .para");         //URL和选择器之间有一个空格   

    load()的传输方式根据参数data指定

    $("#resText").load("test.php",function(){
        });
        //没有参数,是GET方式
    $("#resText").load("test.php",{name:"rain",age:"22"},function(){
        });
        //有参数,是POST方式

    $.get()方法和$.post()方法

    $("#send").click(function(){
           $.get("get1.php",{
                username : $("#username").val(),
                content : $("#content").val()
            },  回调函数)
    })         

    回调函数有两个参数  function( data,textStatus){}      data:返回内容。  textStatus:请求状态 cuccesserror otmodified imeout   4种

    $.post() 方法和get方法相同,他们的区别就是get和post的区别........安全性、传输大小、缓存、服务器端获取方式等

    另外当load()方法带有参数传递时,会使用post方式发送请求,因此也可以使用load()方法来完成同样的功能

    $.ajax()方法,是jQuery最底层的Ajax实现

    可代替之前的所有方法

    如代替 $.getScript()方法

    $(function(){
        $("div").click(function(){
            $.ajax({
            type:"GET",
            url:"test.js",
            dataType:"script"
            })
        })
    })

    Ajax请求开始时,会触发ajaxStart()方法的回调函数,当Ajax结束时,会触发ajaxStop()方法的回调函数,这些方法都是全局的,因为不论他们创建的代码哪里,只要请求发生时,都会触发他们

    例在用户请求过程中,如果较慢,会显示加载中

    <div id="loading">加载中...</div>
    <script type="text/javascript"> $("#loading").ajaxStart(function(){ $(this).show(); }); $("#loading").ajaxStop(function(){ $(this).hide(); }); //也可以使用链式写法 </script>

    如果在页面中其他地方也使用Ajax,该提示仍然有效,因为他是全局的。

    另外几个Ajax全局事件中的方法

    • ajaxComplete(callback)    Ajax请求完成时执行的函数
    • ajaxError(callback)              Ajax请求发生错误时执行的函数
    • ajaxSend(callback)              
    • ajaxStart(callback)
    • ajaxStop(callback)              Ajax请求发送前执行的函数
    • ajaxSuccess(callback)         Ajax请求成功时执行的函数

    如果想使Ajax请求不受全局方法的影响,可以在$.ajax()方法时,将参数中的global设置为false

        $.ajax({
            url:"test.html",
            global:false                //不出发全局Ajax事件
        })
        //在jQuery1.5版本后,如果Ajax请求不出发全局方法,那么可以这么设置
        $.ajaxPrefilter(function(options){
            options.global = true;
        })

     第七章 jQuery插件的使用和写法

    jQuery主要分为3种类型

    1、封装对象方法的插件

    2、封装全局函数的插件

    3、选择器插件

    常见的插件结构

    ;(function($){                      //这里将$作为匿名函数的形参
        //这里放代码,可以使用$作为jQuery的缩写别名
        }) (jQuery)                      //这里将jQuery作为实参传递给了匿名函数

    封装jQuery对象方法的插件

    例:边写一个color()插件,实现以下两个功能

    1、设置匹配元素的背景颜色

    2、获取匹配的元素的背景颜色

    ;(function($){
        $.fn.extend({
            "color":function(value){
            if(value==undefined){
                return this.css("backgroundColor")
            }else{
                return this.css("backgroundColor",value);
            }
            }
        })
    })(jQuery)

      第11章 jQuery性能优化和技巧

    1、使用新版jQuery类库

    2、使用合适的选择器

    使用ID定位是最佳的方式,其他可考虑用find()

    其次是$("p")、$("div")、$("input")

    $("class")较复杂,有选择性的使用

     尽量避免$("[attribute=value]")  这种有害的方式

    伪类选择器尽量避免 $(":hidden")

    3、缓存对象

    避免重复创建选择器,尽量缓存变量,永远不要让相同的选择器在代码里出现多次

    4、循环中的DOM操作

    循环中不要重复创建和查找

    5、数组方式使用jQuery对象

    建议使用简单的for或者while来处理循环,而不是$.each()

    另外注意,检查长度也是检查jQuery对象是否存在的方式

    6、事件代理

    例如on()

    7、将代码转化成jQuery插件

    8、使用json拼接字符串

    尤其是长字符串的处理

    var array=[];
    for(var i=0;i<=10000;i++){
      array[i]='<li>'+i+'</lli>';
    }
    $("#list").html(array.join(''));

    9、合理利用html5的Data属性

    10、尽量使用原声的Javascript方法

    如下代码,它用来判断多选框是否被选中

    var $cr=$("#cr");
    #cr.click(function(){
       if($cr.is(":checked")){
           alert();
       }
    })
    
    
    //它使用是jQuery提供的is() 方法来判断是否被选中,但这里可以使用原生的javascript方法
    
    var $cr=$("#cr");      //jQuery对象
    var cr=$cr.get(0);      //DOM对象,获取$cr[0]
    #cr.click(function(){
       if(cr.checked){
           alert();
       }
    })

    还有很多,例如

    $(this).css("color","red");
    
    //优化成
    
    this.style.color="red";
    
    $("<p></p>");
     
    //优化成
    
    $(document.createElement("p"));

    11、压缩javascript

    jQuery技巧

    1、//禁用页面右键菜单

    $(function(){
        $(document).bind('contextmenu',function(event){
            return false;
        })
    })

    2、//在新窗口打开页面

    $(function(){
        //例子1:href="http://" 的超链接将会在新窗口打开连接
        $('a[href^="http://"]').attr("target","_blank");
    
        //例子2:rel="external"的超链接将会在新窗口打开连接
        $("a[rel$='external']").click(function{
            this.target = "_blank"
        })
    })
    //use
    <a href="http://www...." rel="external">open link</a>

     3、//判断浏览器类型             测试了一下1.9版本不行,1.3版本的可以,其他版本没试,而且判断不准

            $(document).ready(function () {
                if ($.browser.mozilla && $.browser.version >= "1.8") {
                    alert("火狐");
                }
                if ($.browser.safari) {
                    alert("safari");
                }
                if ($.browser.chrome) {
                    alert("chrome");
                }
                if ($.browser.opera) {
                    alert("Opera");
                }
                if ($.browser.msie && $.browser.version <= 6) {
                    alert("IE6-");
                }
                if ($.browser.msie && $.browser.version > 6) {
                    alert("IE6+");
                }
            });

    4、//输入框文字获取和失去焦点

    $(document).ready(function(){
        $('input.text1').val("Enter your search text here");
        textFill($('input.text1'));
    })
    function textFill(input){
        var originalvalue=input.val();
        input.focus(function(){
            if($.trim(input.val())==originalvalue){
                input.val('');
            }
        }).blur(function(){
            if($.trim(input.val())==''){
                input.val(originalvalue);
            }
        })
    }

     5、//返回头部滑动动画

    jQuery.fn.scrollTo = function(speed){
        var targetOffset = $(this).offset().top;
        $('html,body').stop().animate({scrollTop:targetOffset},speed);
        return this;
    }
    //use
    $('#goheader').click(function(){
        $('body').scrollTo(500);
        return false;
    })

    6、//获取鼠标位置

    $(document).ready(function(){
        $(document).mousemove(function(e){
            $('#xy').html("x:"+e.pageX+"|y:"+e.pageY);
        })
    })

     7、//判断元素是否存在

    $(document).ready(function(){
        if($("#id").length){
            alert()
        }
    })

    8、//点击div也可以跳转

    $(document).ready(function(){
        $("div").click(function(){
            window.location=$(this).find("a").attr("href");
            return false;
        })
    })
    //use
    <div><a href="http://www.baidu.com">home</a></div>

    9、//根据浏览器大小添加不同的样式

    $(document).ready(function(){
        function checkWindowSize(){
            if($(window).width()>1200){
                $('body').addClass('large');
            }else{
                $('body').removeClass('large');
            }
        }
      $(window).resize(checkWindowSize)
    })

    10、//设置div在屏幕中央

    $(document).ready(function(){
        jQuery.fn.center=function(){
            this.css("position","absolute");
            this.css("top",($(window).height()-this.height())/2+$(window).scrollTop()+'px');
            this.css("left",($(window).width()-this.width())/2+$(window).scrollLeft()+'px');
        }
    })
    
    //use
        $(".goheader").center();

    11、//创建自己的选择器

    $(document).ready(function(){
        $.extend($.expr[':'],{
            moreThen500px:function(a){
                return $(a).width()>500;
            }
        });
            $('.box:moreThen500px').click(function(){
                alert();
            })
    })

    12、//关闭所有动画效果

    $(document).ready(function(){
        jQuery.fx.off=true;
    })

    13、//检测鼠标的右键和左键

    $(document).ready(function(){
        $(document).mousedown(function(e){
            alert(e.which);       //1-左键;2-中键;3-右键   
        })
    })

    14、//回车提交表单

    $(document).ready(function(){
        $('input').keyup(function(e){
            if(e.which=='13'){
                alert('回车提交')
            }
        })
    })

    15、//设置全局Ajax参数

    $('#load').ajaxStart(function(){
        showLoading();     //显示loading
        disableButtons();   //禁用按钮
    });
    $('#load').ajaxComplete(function(){
        hideLoading();     //隐藏loading
        enableButtons();   //启用按钮
    })

    16、//获取选中的下拉框

    $('#someElemnet').find('option:selected');
    $('#someElemnet option:selected');

    17、//切换复选框

    var tog = false;
    $('button').click(function(){
        $('input[type=checkbox]').prop('checked',!tog);
        tog = !tog;
    })

    18、//使用siblings()来选择同辈元素

    //不这样做
    $('#nav li').click(function(){
        $('#nav li').removeClass('active');
        $(this).addClass('active');
    })
    //替代做法
    $('#nav li').click(function(){
        $(this).addClass('active')
               .siblings().removeClass('active');
    });

    19、//个性化链接

    $(function(){
        $('a[href$="pdf"]').addClass("pdf");
        $('a[href$="zip"]').addClass("zip");
        $('a[href$="psd"]').addClass("psd");
    })

    20、//在一段时间后,自动隐藏或关闭元素

    //setTimeout
    setTimeout(function(){
        $('div').fadeIn(400)
        },3000);
    })
    //1.4之后的版本用delay()
    $('div').slideUp(300).delay(3000).fadeIn(400);

    24、//$.proxy()的使用

    使用回调方法的缺点之一是当执行类库中的方法后,上下文对象被设置到另一个元素,如

    <div id='panel' style='display:none'>
        <button>Close</button>
    </div>

    执行下面代码:

    $('#panel').fadeIn(function(){
        //var that=$(this);
        $('#panel button').click(function(){
            $(this).fadeOut();
        })
    })

    button元素会消失,而不是panel元素 ,可以使用$.proxy方法解决这个问题

    $('#panel').fadeIn(function(){
        $('#panel button').click($.proxy(function(){
            $(this).fadeOut();
            },this
        ))
    })

    可以可以用bind解决

    $('#panel').fadeIn(function(){
        $('#panel button').click(function(){
            $(this).fadeOut();
        }.bind(this))
    })

    当然还有另一种方法

    $('#panel').fadeIn(function(){
        var that=$(this);
        $('#panel button').click(function(){
            that.fadeOut();
        })
    })
  • 相关阅读:
    POJ 1659 Frogs' Neighborhood
    zoj 2913 Bus Pass(BFS)
    ZOJ 1008 Gnome Tetravex(DFS)
    POJ 1562 Oil Deposits (DFS)
    zoj 2165 Red and Black (DFs)poj 1979
    hdu 3954 Level up
    sgu 249 Matrix
    hdu 4417 Super Mario
    SPOJ (BNUOJ) LCM Sum
    hdu 2665 Kth number 划分树
  • 原文地址:https://www.cnblogs.com/change-oneself/p/4811029.html
Copyright © 2011-2022 走看看