jQuery

参考:

(jQuery的类css选择器)jQuery 选择器 | 菜鸟教程

(jQuery的事件方法)jQuery 事件方法 | 菜鸟教程

(jQuery的css方法)jQuery HTML / CSS 方法 | 菜鸟教程

(jQuery的Ajax方法)jQuery AJAX 方法 | 菜鸟教程

目录

jQuery语法

jQuery选择器

元素选择器

#id选择器

.class选择器

jQuery事件

jQuery效果

显示隐藏

淡入淡出

滑动

jQuery动画

 停止动画

回调函数

jQuery html相关

jQuery捕获

设置

添加元素

删除元素

操作css

尺寸

jQuery遍历

祖先

后代

同胞

过滤

jQuery Ajax

load()方法

get()与post()



jQuery 是一个 JavaScript 函数库。

jQuery 是一个轻量级的"写的少,做的多"的 JavaScript 库。

jQuery 库包含以下功能:

  • HTML 元素选取
  • HTML 元素操作
  • CSS 操作
  • HTML 事件函数
  • JavaScript 特效和动画
  • HTML DOM 遍历和修改
  • AJAX
  • Utilities

摘自菜鸟教程

上手:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>
    <script>
        $(document).ready(function(){
            $("p").click(function(){
                $(this).hide();
            })
        })
    </script>
</head>
<body>
    <p>test1(hide by click)</p>
    <p>test1(hide by click)</p>
    <p>test1(hide by click)</p>
    
</body>
</html>

从外部导入jQuery,点击其中的p标签则会hide。

jQuery语法

基础语法: $(selector).action()

dollor符定义jQuery

selector选择器

action对应方法执行操作:

  • $(this).hide() - 隐藏当前元素

  • $("p").hide() - 隐藏所有 <p> 元素

  • $("p.test").hide() - 隐藏所有 class="test" 的 <p> 元素

  • $("#test").hide() - 隐藏 id="test" 的元素

文档就绪事件:

$(document).ready(function(){
 
   // 开始写 jQuery 代码...
 
});

 该文档就绪事件是为了防止文档在加载完成之前就运行jQuery代码,意识就是等dom树都加载完毕后在执行操作。

jQuery选择器

jQuery的选择器基于现有的css选择器,其语法上基本一致

元素选择器

$("p")

#id选择器

$("#test")

.class选择器

$(".test")

jQuery事件

常见 DOM 事件:

鼠标事件键盘事件表单事件文档/窗口事件
clickkeypresssubmitload
dblclickkeydownchangeresize
mouseenterkeyupfocusscroll
mouseleaveblurunload
hover

常用的jQuery事件:

click()

$("p").click(function(){
  $(this).hide();
});

 dbclick()(双击事件)

("p").dblclick(function(){
  $(this).hide();
});

mouseenter()

$("#p1").mouseenter(function(){
    alert('您的鼠标移到了 id="p1" 的元素上!');
});

mouseleave()

$("#p1").mouseleave(function(){
    alert("再见,您的鼠标离开了该段落。");
});

mouseup()

$("#p1").mouseup(function(){
    alert("鼠标在段落上松开。");
});

hover()

$("#p1").hover(
    function(){
        alert("你进入了 p1!");
    },
    function(){
        alert("拜拜! 现在你离开了 p1!");
    }
);

focus()

$("input").focus(function(){
  $(this).css("background-color","#cccccc");
});

blur()

$("input").blur(function(){
  $(this).css("background-color","#ffffff");
});

jQuery效果

显示隐藏

demo:

该demo实现了点击文字隐藏,点击按钮显示

<script>
        $(document).ready(function(){

            $(".hide").click(function(){
                $(this).hide(1000);
            })


            $(".show").click(function(){
                $(".hide").show();
            })
            
        })
    </script>
</head>
<body>


    <div>
        <p class="hide">点击文字隐藏</p>
        <button class="show">点击文字显示</button>
    </div>

语法:

$(selector).hide(speed,callback);

$(selector).show(speed,callback);

其中speed是可以选择的,单位为毫秒

也可以使用回调函数,用以隐藏完毕后alert一个警告框。

toggle()方法,jQuery提供了一个切换两种状态的方法:

$("button").click(function(){
  $("p").toggle();
});

点击button则会一直在显示与隐藏中间切换。

淡入淡出

通过 jQuery,您可以实现元素的淡入淡出效果。

jQuery 拥有下面四种 fade 方法:

  • fadeIn()
  • fadeOut()
  • fadeToggle()
  • fadeTo()

他们的作用与其名称一致。

fadein():

$("button").click(function(){
  $("#div1").fadeIn();
  $("#div2").fadeIn("slow");
  $("#div3").fadeIn(3000);
});

语法:

$(selector).fadeIn(speed,callback);

可选的 speed 参数规定效果的时长。它可以取以下值:"slow"、"fast" 或毫秒。.

可选的 callback 参数是 fading 完成后所执行的函数名称。

fadeout():

$("button").click(function(){
  $("#div1").fadeOut();
  $("#div2").fadeOut("slow");
  $("#div3").fadeOut(3000);
});

与淡入一致。

fadetoggle():

$("button").click(function(){
  $("#div1").fadeToggle();
  $("#div2").fadeToggle("slow");
  $("#div3").fadeToggle(3000);
});

与前两个一致只不过是切换状态。

fadeto():

("button").click(function(){
  $("#div1").fadeTo("slow",0.15);
  $("#div2").fadeTo("slow",0.4);
  $("#div3").fadeTo("slow",0.7);
});

$(selector).fadeTo(speed,opacity,callback);

必需的 speed 参数规定效果的时长。它可以取以下值:"slow"、"fast" 或毫秒。

fadeTo() 方法中必需的 opacity 参数将淡入淡出效果设置为给定的不透明度(值介于 0 与 1 之间)。

滑动

jQuery 拥有以下滑动方法:

  • slideDown()
  • slideUp()
  • slideToggle()

实际用处与名称一致。

slideDown():

语法:

$(selector).slideDown(speed,callback);

可选的 speed 参数规定效果的时长。它可以取以下值:"slow"、"fast" 或毫秒。

可选的 callback 参数是滑动完成后所执行的函数名称。

$("#flip").click(function(){
  $("#panel").slideDown();
});

初始定义id为panel的元素不显示(display:none),在点击按钮后该元素会向下滑动出来

slideUp():

同上

$("#flip").click(function(){
  $("#panel").slideUp();
});

slideToggle():

同上

$("#flip").click(function(){
  $("#panel").slideToggle();
});

demo:

 

<script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>
    <script>
        $(document).ready(function(){

            $(".flip").click(function(){
                $(".panel").slideToggle("slow");

            })

        })


    </script>

    <style>
        .panel,
        .flip{
            border: 5px solid gray;
            background-color: indianred;
            text-align: center;
        }
    </style>
</head>
<body>

    <div>
        <div class="flip">点击滑动panel</div>
        <div class="panel">hello word</div>
    </div>

 

jQuery动画

jQuery animate() 方法用于创建自定义动画。

语法:

$(selector).animate({params},speed,callback);

必需的 params 参数定义形成动画的 CSS 属性。

可选的 speed 参数规定效果的时长。它可以取以下值:"slow"、"fast" 或毫秒。

可选的 callback 参数是动画完成后所执行的函数名称。

demo:

<script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>
    <script>
        $(document).ready(function(){
            $(".btn").click(function(){
                $(".panel").animate({
                    left:"250px",
                    width:"200px",
                    height:"200px",
                    opacity:"0.5"
                })
            })


        })

    </script>
    <style>
        .panel{
            position: relative;
            height: 100px;
            width: 100px;
            border: 5px solid gray;
            background-color: indianred;
        }
    </style>
</head>
<body>
    <div class="panel"></div>
    <button class="btn">点击开始动画</button>

其支持相对值的使用:

$("button").click(function(){
  $("div").animate({
    left:'250px',
    height:'+=150px',
    width:'+=150px'
  });
});

 

 停止动画

$(selector).stop(stopAll,goToEnd);

可选的 stopAll 参数规定是否应该清除动画队列。默认是 false,即仅停止活动的动画,允许任何排入队列的动画向后执行。

可选的 goToEnd 参数规定是否立即完成当前动画。默认是 false。

因此,默认地,stop() 会清除在被选元素上指定的当前动画。

下面的例子演示 stop() 方法,不带参数:

$("#stop").click(function(){
  $("#panel").stop();
});

demo(参见菜鸟教程):菜鸟教程在线编辑器

回调函数

$("button").click(function(){
  $("p").hide("slow",function(){
    alert("段落现在被隐藏了");
  });
});

上述demo是使用回调函数

会在隐藏效果完成后弹出一个警告框显示段落现在被隐藏了

$("button").click(function(){
  $("p").hide(1000);
  alert("段落现在被隐藏了");
});

上述demo不使用回调函数,会在段落被隐藏前弹出警告框。

类似于JavaScript函数式编程思想

可以建立一个链来对一个标签进行重复操作

$("#p1").css("color","red")
  .slideUp(2000)
  .slideDown(2000);

jQuery html相关

jQuery捕获

三个简单实用的用于 DOM 操作的 jQuery 方法:

  • text() - 设置或返回所选元素的文本内容
  • html() - 设置或返回所选元素的内容(包括 HTML 标记)
  • val() - 设置或返回表单字段的值

demo:

$("#btn1").click(function(){
  alert("Text: " + $("#test").text());
});
$("#btn2").click(function(){
  alert("HTML: " + $("#test").html());
});

$("#btn1").click(function(){
  alert("值为: " + $("#test").val());
});

获取属性attr()

$("button").click(function(){
  alert($("#runoob").attr("href"));
});

设置

上述捕获的所有方法在方法中是可以进行设置值的:

demo:

$("#btn1").click(function(){
    $("#test1").text("Hello world!");
});
$("#btn2").click(function(){
    $("#test2").html("<b>Hello world!</b>");
});
$("#btn3").click(function(){
    $("#test3").val("RUNOOB");
});

这些方法是有回调函数的

demo:

$("#btn1").click(function(){
    $("#test1").text(function(i,origText){
        return "旧文本: " + origText + " 新文本: Hello world! (index: " + i + ")"; 
    });
});
 
$("#btn2").click(function(){
    $("#test2").html(function(i,origText){
        return "旧 html: " + origText + " 新 html: Hello <b>world!</b> (index: " + i + ")"; 
    });
});

有两个属性:i与origText,其中i是被选元素中当前元素的下标,orIgText是原内容。

attr属性设置:

$("button").click(function(){
  $("#runoob").attr("href","http://www.runoob.com/jquery");
});

其接受多个属性的设置:
$("button").click(function(){
    $("#runoob").attr({
        "href" : "http://www.runoob.com/jquery",
        "title" : "jQuery 教程"
    });
});

添加元素

用原生JavaScript操作dom添加元素是非常复杂的,首先要先定义元素,再向元素中添加内容,之后才可以添加到dom当中。

而jQuery提供的添加元素方法非常简便,

demo:

function appendText(){
    var txt1="<p>文本-1。</p>";              // 使用 HTML 标签创建文本
    var txt2=$("<p></p>").text("文本-2。");  // 使用 jQuery 创建文本
    var txt3=document.createElement("p");
    txt3.innerHTML="文本-3。";               // 使用 DOM 创建文本 text with DOM
    $("body").append(txt1,txt2,txt3);        // 追加新元素
}

我们将学习用于添加新内容的四个 jQuery 方法:

  • append() - 在被选元素的结尾插入内容
  • prepend() - 在被选元素的开头插入内容
  • after() - 在被选元素之后插入内容
  • before() - 在被选元素之前插入内容

append():

$("p").append("追加文本");

在元素内部的结尾追加

prepend():

$("p").prepend("在开头追加文本");

在元素内部的开头追加文本

这两个方法可以接受无限参数的新元素添加到html当中。(开头的demo)

after与before方法:

$("img").after("在后面添加文本");
 
$("img").before("在前面添加文本");

注意区别于append与prepend,该方法是向元素后添加的(不在元素内部添加)

function afterText()
{
    var txt1="<b>I </b>";                    // 使用 HTML 创建元素
    var txt2=$("<i></i>").text("love ");     // 使用 jQuery 创建元素
    var txt3=document.createElement("big");  // 使用 DOM 创建元素
    txt3.innerHTML="jQuery!";
    $("img").after(txt1,txt2,txt3);          // 在图片后添加文本
}

由这两种方式我们可以随便在自己选择的元素后添加新元素

删除元素

如需删除元素和内容,一般可使用以下两个 jQuery 方法:

  • remove() - 删除被选元素(及其子元素)
  • empty() - 从被选元素中删除子元素

remove是删除被选元素的全部,而empty仅仅只是删除备选元素的子元素

$("#div1").remove();

$("#div1").empty();

$("p").remove(".italic");

操作css

jQuery 拥有若干进行 CSS 操作的方法。

  • addClass() - 向被选元素添加一个或多个类
  • removeClass() - 从被选元素删除一个或多个类
  • toggleClass() - 对被选元素进行添加/删除类的切换操作
  • css() - 设置或返回样式属性

.important
{
        font-weight:bold;
        font-size:xx-large;
}
 
.blue
{
        color:blue;
}


$("button").click(function(){
  $("h1,h2,p").addClass("blue");
  $("div").addClass("important");
});

$("button").click(function(){
  $("body div:first").addClass("important blue");
});


$("button").click(function(){
  $("body div:first").addClass("important blue");
});

相当于向元素添加了一个class,而根据样式表中已经规定了

删除class:

$("button").click(function(){
  $("h1,h2,p").removeClass("blue");
});

删除添加(切换)class:

$("button").click(function(){
  $("h1,h2,p").toggleClass("blue");
});

css()方法:

css()方法可以用来返回样式的值或者对样式的值进行一个设置:

$("p").css("background-color");
//返回背景颜色

css("propertyname","value");
//设置样式值

$("p").css("background-color","yellow");

$("p").css({"background-color":"yellow","font-size":"200%"});
//设置多个样式值

尺寸

jQuery Dimensions

 jQuery对尺寸的获取遵循该图的原则

$("button").click(function(){
  var txt="";
  txt+="div 的宽度是: " + $("#div1").width() + "</br>";
  txt+="div 的高度是: " + $("#div1").height();
  $("#div1").html(txt);
});
//不包括内边距与边框

$("button").click(function(){
  var txt="";
  txt+="div 宽度,包含内边距: " + $("#div1").innerWidth() + "</br>";
    txt+="div 高度,包含内边距: " + $("#div1").innerHeight();
  $("#div1").html(txt);
});
//包括内边距

$("button").click(function(){
  var txt="";
  txt+="div 宽度,包含内边距和边框: " + $("#div1").outerWidth() + "</br>";
  txt+="div 高度,包含内边距和边框: " + $("#div1").outerHeight();
  $("#div1").html(txt);
});
//包括内边距与边框

jQuery遍历

jQuery的遍历意为移动,

祖先

向上遍历 DOM 树:

  • parent()
  • parents()
  • parentsUntil()

parent()会返回当前元素的一个直接父元素

$(document).ready(function(){
  $("span").parent();
});

parents()会返回当前元素一直到根元素的所有父级元素

$(document).ready(function(){
  $("span").parents();
});

它的参数是可以选择的,返回的是符合参数的那个元素

$(document).ready(function(){
  $("span").parents("ul");
});

parentsUntil,会直到符合条件元素的参数的所有父级元素

$(document).ready(function(){
  $("span").parentsUntil("div");
});

后代

下面是两个用于向下遍历 DOM 树的 jQuery 方法:

  • children()
  • find()

children():

$(document).ready(function(){
  $("div").children();
});

该段demo返回div标签的所有子树

该方法的参数是可选的,如果添加参数则会有参数的一个过滤规则:

$(document).ready(function(){
  $("div").children("p.1");
});

上述代码返回类型为1的所有后代p

find():

$(document).ready(function(){
  $("div").find("span");
});

该demo与上述带参数的children作用一致

寻找所有的子元素:

$(document).ready(function(){
  $("div").find("*");
});

同胞

 DOM 树进行水平遍历:

  • siblings()
  • next()
  • nextAll()
  • nextUntil()
  • prev()
  • prevAll()
  • prevUntil()

siblings():

返回所有的同代元素:

$(document).ready(function(){
  $("h2").siblings();
});
//其参数也是一个过滤规则

$(document).ready(function(){
  $("h2").siblings("p");
});

next():

返回当前元素的下一个后代元素:

$(document).ready(function(){
  $("h2").next();
});

nextuntil():

返回当前元素直到参数元素的所有同胞元素

$(document).ready(function(){
  $("h2").nextUntil("h6");
});

其余元素仅仅只是相反方向进行了同样的操作。

过滤

过滤分别有first(),last(),eq()

first():

$(document).ready(function(){
  $("div p").first();
});

该demo 返回首一个div当中的第一个p元素

last():

$(document).ready(function(){
  $("div p").last();
});

该代码返回最后一个p元素

eq():

该方法有一个参数当做索引,给定的数字为第几个元素

$(document).ready(function(){
  $("p").eq(1);
});

(索引从零开始)所以上述代码返回寻找到的p元素的第二个元素

filter():

该方法的参数做一个过滤的作用,符合参数条件的会被保留下来,其余的元素会被删除。

$(document).ready(function(){
  $("p").filter(".url");
});

该方法返回的是所有p标签带有url类名的元素。

not():

该方法与上述filter刚好相反,返回的是不满足参数条件的所有元素。

jQuery Ajax

load()方法

$(selector).load(URL,data,callback);

url参数为你想加载资源的url地址

data参数为发送查询的键值对集合

callback为回调函数会在load方法完成后执行

$("button").click(function(){
  $("#div1").load("demo_test.txt",function(responseTxt,statusTxt,xhr){
    if(statusTxt=="success")
      alert("外部内容加载成功!");
    if(statusTxt=="error")
      alert("Error: "+xhr.status+": "+xhr.statusText);
  });
});

重写其回调函数时有三个参数:

responseTxt为调用成功时的结果内容

statusTxt包含调用的状态

xhr包含XMLHttpRequest对象。

get()与post()

jQuery当中有get与post两个方法来帮助用户便捷的从服务器请求数据

$.get(URL,callback);

必选参数url制定需要获取资源的url地址,

callback回调函数会在get方法执行后进行操作。

$("button").click(function(){
  $.get("demo_test.php",function(data,status){
    alert("数据: " + data + "\n状态: " + status);
  });
});



<?php
echo '这是个从PHP文件中读取的数据。';
?>

$.post(URL,data,callback);

与get相比仅仅是多了一个data来设置与请求一起发送的数据

$("button").click(function(){
    $.post("/try/ajax/demo_test_post.php",
    {
        name:"菜鸟教程",
        url:"http://www.runoob.com"
    },
    function(data,status){
        alert("数据: \n" + data + "\n状态: " + status);
    });
});



<?php
$name = isset($_POST['name']) ? htmlspecialchars($_POST['name']) : '';
$url = isset($_POST['url']) ? htmlspecialchars($_POST['url']) : '';
echo '网站名: ' . $name;
echo "\n";
echo 'URL 地址: ' .$url;
?>

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值