jquery学习笔记及常用函数封装

二、JQuery

学习笔记及常用函数封装
https://download.csdn.net/download/weixin_42530002/13087988

1、JQuery入门
(1)、css选择
(2)、css独有的表达式
(3)、多种筛选方式 filter
(4)、方法函数化
(5)、链式操作
(6)、取值赋值合体
(7)、JQuery和JS的关系
(8)、has filter not
(9)、prev next
(10)、find
(11)、eq和index方法
(12)、attr
(13)、addClass removeClass
(14)、width系列三个方法
(15)、节点操作
(16)、on off
(17)、scrollTop
(18)、案例 弹窗 可随scroll resize改变而改变
(19)、事件的细节
(20)、offset position
(21)、案例 拖拽JQ 及 JS
(22)、案例 选项卡JQ 及 JS

2、JQuery进阶
(1)、val each size
(2)、特效函数
(3)、animate 日历 选项卡
(4)、animate补充
(5)、remove detach
(6)、ready
(7)、text html
(8)、节点操作
(9)、parents closest
(10)、wrap
(11)、clone
(12)、add slice
(13)、数据串联化
(14)、事件细节 trigger
(15)、JQ的工具方法
(16)、JQ的插件方法
(17)、get JQ -> JS
(18)、JQuery.cookie
(19)、JQuery_ajax 支持JSONP
3、JQuery实战
(1)、构造函数
(2)、JQuery_ajax load get post
(3)、案例 JQuery放大镜
(4)、案例 JQuery banner滚动轮播图

1、JQuery入门
(1)、css选择

<script src = 'jquery-1.10.1.min.js'></script>

/* 
    JQuery版本区别
        1.0  可以兼容到IE8以下
        2.0  只兼容IE8以上
        3.0
    【注】JQuery中文文档。

        JQ的设计思想
            1、模拟css选择网页元素    
*/

//#id
//  $("#div1").css("backgroundColor", 'red');

//.class
// $(".box").css("backgroundColor", 'red');

//tagName
// $("ul li").css("backgroundColor", 'blue');

$("[name=hello]").css("backgroundColor", 'yellow');

(2)、css独有的表达式
// $(“li”).css(“backgroundColor”, ‘red’);

//表达式的写法
// $("li:first").css("backgroundColor", 'red');
// $("li:last").css("backgroundColor", 'red');

//比较高级的表达式写法
// $("li:even").css("backgroundColor", 'red');

// $("li:odd").css("backgroundColor", 'blue');

//eq从0开始
$("li:eq(2)").css("backgroundColor", 'red');

(3)、多种筛选方式 filter
// $(“li:eq(2)”).css(“backgroundColor”, ‘red’);
// $(“li”).eq(2).css(“backgroundColor”, ‘red’);

// $("li.box").css("backgroundColor", 'blue');

$("li").filter(".box").css("backgroundColor", 'yellow');

(4)、方法函数化
/*
【注】在JQ中基本上见不到等于号。所有的赋值操作都是函数传参的操作。
*/
$(function(){
//添加一个点击事件
$(“h1”).click(function(){
alert(“我被点击了”);
})

    //后续所有的事件绑定大家都会了,都是一样的套路
    $("h1").mouseover(function(){
        this.style.backgroundColor = 'red';
    })

    $("h1").mouseout(function(){
        this.style.backgroundColor = 'blue';
    })
});

(5)、链式操作
( " h 1 " ) . c l i c k ( f u n c t i o n ( ) a l e r t ( " 单 击 " ) ; ) . c s s ( " b a c k g r o u n d C o l o r " , ′ o r a n g e ′ ) . m o u s e o v e r ( f u n c t i o n ( ) t h i s . s t y l e . b a c k g r o u n d C o l o r = ′ r e d ′ ; ) . m o u s e o u t ( f u n c t i o n ( ) t h i s . s t y l e . b a c k g r o u n d C o l o r = ′ b l u e ′ ; ) ( 6 ) 、 取 值 赋 值 合 体 / ∗ i n n e r H T M L v a l u e ∗ / a l e r t ( ("h1").click(function(){ alert("单击"); }) .css("backgroundColor", 'orange') .mouseover(function(){ this.style.backgroundColor = 'red'; }).mouseout(function(){ this.style.backgroundColor = 'blue'; }) (6)、取值赋值合体 /* innerHTML value */ alert( ("h1").click(function()alert("");).css("backgroundColor",orange).mouseover(function()this.style.backgroundColor=red;).mouseout(function()this.style.backgroundColor=blue;)(6)/innerHTMLvalue/alert(("#div1").html());
$("#div1").html(“

我是新赋值的内容

”) */

alert($("input").val());
$("input").val("world hello");

(7)、JQuery和JS的关系
/*
JQuery和JS可以共存,但是不能混用。
/
// alert(KaTeX parse error: Expected 'EOF', got '#' at position 3: ("#̲div1").innerHTM…("#div1").html());
(8)、has filter not
/

filter 过滤 对已经获取到的网页元素进行过滤
not filter的反义词
has 拥有,直接判定<子节点>中是否有符合条件的元素。
*/
$(function(){
// $(“div”).filter(".box").css(“backgroundColor”, ‘orange’);

    // $("div").not(".box").css("backgroundColor", 'orange');

    // $("div").has(".box").css("backgroundColor", 'orange');
})

(9)、prev next
/*
prev 查找当前兄弟节点中的上一个节点
next 查找当前兄弟节点中的下一个节点
*/
$(function(){
$(“h3”).prev().css(“backgroundColor”, ‘red’);

    $("h3").next().css("backgroundColor", 'blue');
})

(10)、find
/*
find 查找子节点 所有子节点
*/
$(function(){
// $(“li”).css(“backgroundColor”, ‘red’);

    /*  $("ul").find("li").css("backgroundColor", 'blue');
    $("ul li"); */

    // $("ul").find(".box").css("backgroundColor", 'blue');

    $("ul").find("[name=hello]").css("backgroundColor", 'blue');
})

(11)、eq和index方法
/*
index() 获取当前节点在兄弟节点中的下标
eq(下标) 通过下标获取指定的元素节点
/
KaTeX parse error: Expected '}', got 'EOF' at end of input: … alert((“h3”).index());
$(“li”).eq(3).css(“backgroundColor”, ‘orange’);
$(“li:eq(4)”).css(“backgroundColor”, ‘yellow’);
})
(12)、attr
/

attr 设置和修改行间属性
*/
KaTeX parse error: Expected '}', got 'EOF' at end of input: … /* alert(("#div1").attr(“id”));
alert(KaTeX parse error: Expected 'EOF', got '#' at position 3: ("#̲div1").attr("ti…("#div1").attr(“class”)); */

    //设置属性值
    /*  $("#div1").attr("title", 'world');
    $("#div1").attr("class", 'box22') */

    //一次性修改多条属性
    $("#div1").attr({
        title: 'world',
        class: "xxxx",
        yyy: "zzz"
    })
})

(13)、addClass removeClass
/*
addClass()
removeClass()

    【注】操作class属性
*/
$(function(){
    //为集合形式 重复则只保留一个
    $("#div1").addClass("box3 box4 box2");

    //不存在不会报错
    $("#div1").removeClass("box2 box3");
})

(14)、width系列三个方法
// width() innerWidth() outerWidth()
// height() innerHeight() outerHeight()
/*
offsetWidth width + border + padding
/
KaTeX parse error: Expected '}', got 'EOF' at end of input: … // alert(("#div1").css(“width”)); //“100px” 字符串
alert(KaTeX parse error: Expected 'EOF', got '#' at position 3: ("#̲div1").width())…("#div1").innerWidth()); //width + padding
alert(KaTeX parse error: Expected 'EOF', got '#' at position 3: ("#̲div1").outerWid…("#div1").outerWidth(true)); //width + border + padding + margin
})
(15)、节点操作
/

• insertBefore() before() //主谓关系
• insertAfter() after() //主谓关系
• appendTo() 插入到子节点的末尾 appendChild(类似JS的方法)
append()
• prependTo() 插入到子节点的首位 prepend()
• remove()
*/
$(function(){
//找到span节点插入到div的前面
// ( " s p a n " ) . i n s e r t B e f o r e ( ("span").insertBefore( ("span").insertBefore((“div”));

    //找到div节点,插入到span节点的后面
    // $("div").insertAfter($("span"));

    //找到span节点,插入到div节点的子节点的末尾
    // $("span").appendTo($("div"));

    //找到span节点,插入到div节点子节点的首位
    // $("span").prependTo($("div"));

    // $("div").remove();

    //找到span节点插入到div的前面
    // $("span").insertBefore($("div")).css("backgroundColor", 'red');

    //div节点前面是span
    $("div").before($("span")).css("backgroundColor", 'red');
})

(16)、on off
/*
$().click(function(){

    })
    
    on和off方法
*/

//1、给一个事件添加一个函数
/*  
    $("#div1").on("click", function(){
        alert("hello");
    }) */

    //2、同时给多个事件添加一个函数, 多个事件之间可以通过空格隔开
    /* var i = 0;
    $("#div1").on("click mouseover", function(){
    $(this).html(i++);
    }) 
*/

//3、给不同的事件添加不同的函数
$("#div1").on({
    click: function(){
        alert("点击");
    },
    mouseover: function(){
        $(this).css("backgroundColor", 'orange');
    },
    mouseout: function(){
        $(this).css("backgroundColor", 'blue');
    }
})

$("#div1").click(show);

function show(){
    alert("show");
}

//4、事件委托
/* 
第二个参数,是触发对象的选择器
*/
/* $("ul").on("click", "li.box", function(){
$(this).css("backgroundColor", 'red');
})

var i = 6;
$("#btn1").click(function(){
    //新增li节点
$(`<li class = 'box'>${i++ * 1111}</li>`).appendTo($("ul"));
}) */

$("#cancel").click(function(){
// $("#div1").off(); //取消所有事件上的所有函数
// $("#div1").off("click"); //取消某一个事件下的所有函数 一个事件可以绑定多个函数

$("#div1").off("click", show); //取消某一个事件下指定的函数
})

(17)、scrollTop
$(function(){
KaTeX parse error: Expected '}', got 'EOF' at end of input: … alert((window).scrollTop()); //输出滚动高度。
})
})
(18)、案例 弹窗 可随scroll resize改变而改变
(19)、事件的细节
/*
【注】都是兼容的后。
• ev pageX

    which  
        鼠标事件:button
        1 左键
        2 滚轮
        3 右键

        keydown: keyCode 键码
        keypress: charCode 字符码

    • preventDefault stopPropagation
    阻止默认行为        阻止事件冒泡
    【注】大家不能为了使用JQ而使用JQ。如果实际开发的时候JS一些比较的简单的操作,没必要写成JQ代码。
*/
$("div").click(function(ev){
    alert(this.id);

    ev.stopPropagation();
})
$("a").click(function(ev){
/*  ev.preventDefault();
    ev.stopPropagation(); */

    //既阻止事件冒泡,又阻止默认行为
    return false;
})

$(document).mousedown(function(ev){
/*  alert(ev.pageX + ", " + ev.pageY); //带滚动距离
alert(ev.clientX + ", " + ev.clientY); //可视窗口为原点 */

alert(ev.which);
})

/* $(window).keydown(function(ev){
    alert(ev.which);
}) */

$(window).keypress(function(ev){
    alert(ev.which);
})

(20)、offset position
/*
有定位的节点 css有定义position
• offset() 直接获取当前元素,距离最左边的距离,margin不算数的。
• position() 直接获取,当前元素,距离第一个有定位父节点的距离,margin算在内
• offsetParent() 查找第一个有定位的父节点,如果父节点没有定位就继续往上去找,最终找到html节点。
*/
KaTeX parse error: Expected '}', got 'EOF' at end of input: … // alert(("#div2").offset().left);

    // alert($("#div2").position().left)
    // alert($("#div2").position().top)

    $("#div2").offsetParent().css("backgroundColor", 'yellow');
})

(21)、案例 拖拽JQ 及 JS
(22)、案例 选项卡JQ 及 JS

2、JQuery进阶
(1)、val each size

/*
val() value 获取/设置表单元素的值

    size() 输出,获取网页元素的个数 =.length

    each() 遍历
*/
// alert($("input").val()); //JQ取值只能去第一个符合条件元素的值

// $("input").val("hello world"); //JQ赋值批量操作,会对所有获取到的元素进行赋值。
/* 
    css()
    attr()
    html()
    【注】都是批量操作。
*/

/* alert($('input').size());
alert($("input").length); */

$("input").each(function(index, item){
    // alert(item + ", " + index);
    // item.value = index;

    $(item).val(index);
})

(2)、特效函数

/*
hover(funcOver, funcOut)

    hide() 隐藏
        第一个参数:动画持续的毫秒数
        第二个参数:回调函数,动画结束的时候执行的
    show() 显示
    【注】动画效果是,从左上角收起和从左上角展开


    slideDown()
    slideUp()   动画效果是卷闸效果。


    fadeIn()   淡入
    fadeOut()  淡出
    fadeTo(动画持续时间,  透明度0~1, 回调函数);
*/
$(function(){
    $("#div1").hover(function(){
        // $(this).html("移入");

        /*  $("#div2").hide(2000, function(){
            $("#div1").html("移入")
        }); */

        /*  $("#div2").slideUp(2000, function(){
            $("#div1").html("移入")
        }); */
        /* $("#div2").fadeOut(2000, function(){
            $("#div1").html("移入")
        }); */

        $("#div2").fadeTo(2000, 0.5, function(){
            $("#div1").html("移入")
        });
    }, function(){
        // $(this).html("移出");

        /* $("#div2").show(2000, function(){
            $("#div1").html("移出")
        }); */

        /*  $("#div2").slideDown(2000, function(){
            $("#div1").html("移出")
        }); */

        /*  $("#div2").fadeIn(2000, function(){
            $("#div1").html("移出")
        }); */
        $("#div2").fadeTo(2000, 1, function(){
            $("#div1").html("移出")
        });
    })
})

(3)、animate 日历 选项卡

/* 
    hover(funcOver, funcOut)

    hide() 隐藏
        第一个参数:动画持续的毫秒数
        第二个参数:回调函数,动画结束的时候执行的
    show() 显示
    【注】动画效果是,从左上角收起和从左上角展开

    slideDown()
    slideUp()   动画效果是卷闸效果。

    fadeIn()   淡入
    fadeOut()  淡出
    fadeTo(动画持续时间,  透明度0~1, 回调函数);

    animate
        默认的运动形式是 慢快慢
            匀速   "linear"
            慢快慢  "swing"
    拓展更多animate的运动形式:
        引入 jquery-ui
*/
$("#div2").animate({
    width: 300,
    height: 300,
    opacity: 0.5
}, 4000, function(){
    $("#div1").html("移入");
})

(4)、animate补充
/*
停止动画的函数

    delay()  延迟
*/
// 小技巧:
//     我们可以在每次调用animate之前先去调用一次stop关闭上一次定时器

$("#div1").click(function(){
    $("#div1").animate({width: 300}, 2000).delay(4000).animate({height: 300}, 2000);
})

$("#div2").click(function(){
    // $("#div1").stop(); //停止第一个动画,当时后续动画正常运动
    // $("#div1").stop(true); //停止所有动画
    // $("#div1").stop(true, true); //停止所有动画,并且将当前正在进行的动画,直接到达目的值
    $("#div1").finish(); //停止所有动画,并且将所有的动画都到达目的值
})

(5)、remove detach
/*
remove() 删除元素节点
【注】并不会保留这个元素节点上之前的事件和行为

    detach() 删除元素节点
        【注】会保留这个元素节点上之前的事件和行为
*/
//remove 返回值就是我们删除这个节点
var node = $("#div1").remove();
var node = $("#div1").detach();
node.appendTo($("#div2"));

(6)、ready
/*
ready 事件
$(document).ready() 事件触发在当前的document加载完成以后执行。

    window

    document加载完毕肯定是在window加载完毕之前。
*/
//3
window.onload = function(){
    alert("我是onload")
}

$(function(){
    //相当于window.onload
    alert(1);
})
$(document).ready(function(){
    alert(2);
})

(7)、text html
/*
JQuery 标签间的内容 html() 相当于innerHTML
JQuery 标签间纯文本 text() 相当于innerText
/
(8)、节点操作
/

节点操作的方法
【注】下述所有的方法的参数都是选择器
siblings() 用来除当前节点外,所有的兄弟节点
nextAll() prevAll()
parentsUntil() nextUntil() prevUntil()
均不包含当前节点与目标节点 只取中间节点
*/

// $("#p1").siblings().css("backgroundColor", 'blue');

// $("#p1").nextAll().css("backgroundColor", 'red');

// $("#p1").prevAll("h1").css("backgroundColor", 'red');

// $("#p1").nextUntil("strong").css("backgroundColor", 'orange');

// $("#p1").prevUntil("h1").css("backgroundColor", 'orange');

$("#p1").parentsUntil("body").css("backgroundColor", 'green');

(9)、parents closest
/*
parent() 获取父节点 第一个符合条件的
parents() 获取父节点们 参数选择器
closest() 必须传入参数,参数也是选择器,只获取第一个符合条件的元素,从自己开始去查找的
包含自己和目标
*/
$(function(){
// $("#div2").parent().css(“backgroundColor”, ‘red’);

    // $("#div2").parents(".box").css("backgroundColor", 'red');
    $("#div2").closest("#div1").css("backgroundColor", 'red');
})

(10)、wrap
/*
wrap() 每一个获取到的元素节点单独包装
wrapAll() 整体包装 整体打包到第一个节点位置
wrapInner() 内部包装
unwrap() 删除包装 删除上面一层包装,不包括body节点
*/
$(function(){
//我们给页面上所有的span节点加一个包装,直接JQ创建节点的代码
// $(“span”).wrap("

");
// $(“span”).wrapAll("

");
// $(“span”).wrapInner("

");
    $("span").unwrap(); //没有参数
})

(11)、clone
/*
clone() 默认只会克隆节点本身,并不会克隆我们元素节点的行为和事件
clone(true) 既会克隆节点本身,还会克隆元素节点的行为和事件
/
var node = KaTeX parse error: Expected 'EOF', got '#' at position 3: ("#̲div1").clone(tr…("#div2"));
(12)、add slice
/

add() 可以将多个选择器拼接在一起
$(“div”).add(“span”).add(“ul li”) == $(“div,span,ul li”)

    slice()  slice(start, end) [start, end)
    获取指定范围内获取到的元素节点。
*/

(13)、数据串联化
/*
serialize() 将我们表单中的数据拼接成querystring(查询字符串) name1=value1&name2=value2
search ?name1=value1&name2=value2
querystring name1=value1&name2=value2

    serializeArray()  将表单数据拼接成数组
*/
alert($("input").serialize()); //a=1&b=2&c=3
console.log($("input").serializeArray()) 
    Array(3)
        0: {name: "a", value: "1"}
        1: {name: "b", value: "2"}
        2: {name: "c", value: "3"}

(14)、事件细节 trigger
/*
• trigger() 主动触发
• ev.data

    ev.target(兼容后触发对象) 
    ev.type(输出事件类型)
    
    trigger() 可以触发官方定义的事件以外
                还可以触发我们自定义的事件
    音乐播放器
*/
/* $("button").click(function(ev){
    alert(ev.type);     //click
    alert(ev.target);   //button
}) */

//配合on使用 
/* $("button").on("click", {username: "钢铁侠", age: 18}, function(ev){
    alert(ev.data); //拿到传入的参数
    alert(ev.data.username);
    alert(ev.data.age);

    alert(1);
})

$("#play").on("play", function(){
    alert("开始播放音乐");
})

$("#play").on("next", function(){
    alert("切换到下一首歌曲");
})
$("button").eq(0).click(function(){
    $("#play").trigger("play");
})
$("button").eq(1).click(function(){
    $("#play").trigger("next");
})

(15)、JQ的工具方法
/*
JQ的工具方法和我们自己封装的js方法没有任何区别。
$()下的常用方法(都没用了,ECMA5和ECMA6类似功能的函数)

        JQ的方法调用:$().xxx() $().yyy()  必须JQ对象调用这个函数
        JQ的工具方法:$.xxx() $.yyy()

            • type()  输出当前数据类型   typeof
            • trim()
            • inArray()    indexOf()
            • proxy()    功能类似于bind  $.proxy()
            • noConflict()
            • $.parseJSON()   JSON.parse()
            • makeArray()    将伪数组转成数组。 Array.from()
*/
var nodes = document.getElementsByTagName("div");
// nodes.push("hello"); //伪数组
// nodes = $.makeArray(nodes);
nodes = Array.from(nodes);
nodes.push("hello");
alert(nodes);

(16)、JQ的插件方法
/*
$.extend() 拓展工具方法 $.xxx() $.yyy()
$.fn.extend() 拓展JQ方法 $().xxx() $().yyy()

    JQ插件方法,如果我们想要给JQ新增函数,通过上述两个插件方法拓展函数库。
*/
$.extend({
    aaa: function(){
        alert("这是一个工具方法");
    }
})
$.fn.extend({
    aaa: function(){
        alert("这是一个JQ方法");
    },
$.aaa();
$("div").aaa(); 

(17)、get JQ -> JS
/*
可以将前面的JQ对象转成JS对象
get()传入下标,获取指定的元素。
*/
$(“div”).get(1).innerHTML = ‘hello world’;
$(“div”)[1].innerHTML = ‘hello world’;
(18)、JQuery.cookie

/* 
    $.cookie()

    具体调用的格式
    $.cookie(name) 通过name取值
    $.cookie(name, value) 设置name和value
    $.cookie(name, value {
        可选项
        raw: true  value不进行编码
            默认false value要进行编码的
    })
    $.cookie(name, null); 删除cookie
*/
alert($.cookie("变种人"));
alert($.cookie("赛亚人"));
alert($.cookie("海贼王"));

$(function(){
    $("#btn1").click(function(){
        $.cookie("赛亚人", null);
        alert($.cookie("赛亚人"));
    })
})

(19)、JQuery_ajax 支持JSONP
/*
$().load()
$.get()
$.post()
/
/
$.ajax({
type: “get”,
url: “1.txt”,
data: {

    },
    success: function(data, statusText, xhr){
        
        // statusText success  error
        // xhr ajax对象
        
    alert(data + ", " + statusText);
    },
    error: function(msg){
        alert(msg);
    }
}) */

$.ajax({
    type: "get",
    url: "https://api.asilu.com/weather/",
    data: {
        city: "青岛"
    },
    dataType: "jsonp",
    success: function(data, statusText){
    // alert(data + ", " + statusText);
    console.log(data);
    
    },
    error: function(msg){
        alert(msg);
    }
})

3、JQuery实战
(1)、构造函数
/*
构造函数
*/
function Person(name, sex){
this.name = name;
this.sex = sex;
}
Person.prototype.showName = function(){
alert(“我的名字叫” + this.name);
return this;
}
Person.prototype.showSex = function(){
alert(“我的性别是” + this.sex);
return this;
}

function $(name, sex){
    return new Person(name, sex);
}

$("blue", "男").showName().showSex().showName().showSex();

(2)、JQuery_ajax load get post
/*
load方法
将url传入以后,将下载到数据直接填充到被选中元素的innerHTML中
*/
$(function(){

    $("button").eq(0).click(function(){
        $("div").load("2.txt #p1", function(data, statusText, xhr){
            /* 
                data 下载到的数据
                statusText  下载的状态  success
                xhr ajax对象
            */
            /*  alert(data + ", " + statusText);
            alert(xhr.status); */
        })
    })

    /* $("button").eq(1).click(function(){
        
        $.get("2.txt", function(data, statusText, xhr){
            alert(data);
        })
    }) */

    $("button").eq(2).click(function(){
        
        $.post("1.post.php", {
            username: 'tian',
            age: 19,
            password: "123abc"
        }, function(data, statusText, xhr){
            alert(data);
        })
    })
})

(3)、案例 JQuery放大镜
(4)、案例 JQuery banner滚动轮播图

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值