1.jQuery初识
1.1 jQuery是优秀JavaScript库
-
解决了兼容问题
-
简化获取标签、DOM操作、事件、动画、ajax
-
强大的选择器功能(通过选择器选择标签)$(“选择器”)
-
函数化(方法化) 语法:$(“选择器”).action();
-
取值赋值一体
//赋值 $("div").html("<strong>发卡福建安防</strong>"); //取值 var text = $("div").html(); console.log(text); //<strong>发卡福建安防</strong>
-
链式操作
$(this).css("background","teal").siblings().css("background",""); $(this).css("width",100).css("height",100)
1.2 引入
-
网站
- 官网:jquery.com
- 中文官网:https://www.bootcdn.cn/jquery/
-
版本
- 最新:3.5.1
- 使用:2版本以下,2以上版本不兼容IE
<!-- 引入本地的 --> <!-- <script src="./js/jquery-1.9.1.js"></script> --> <!-- 引入CDN(内容分发网)上的 --> <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.js"></script> <script> $("div").css({"width":100,"height":100,"background":"teal"}); </script>
1.3 jquery的加载
- ready
// jquery的加载 ready
$(document).ready(function () {
//window.jQuery = window.$ = jQuery; 别名
$("div").css("width", 100);
});
$().ready(function(){
$("div").css("height",100);
});
$(function(){
$("div").css("background","teal");
});
- window.onload和ready方法的区别
- window.onload
- 等文档和资源都加载完成后执行
- 多个事件覆盖
- ready
- 等文档加载完成后就执行
- 多个事件叠加
- window.onload
1.4 jQuery和DOM对象的关系
- jQuery对象:通过$(“选择器”)
- DOM对象:通过document获取,具体的标签或元素集合
//1.获取元素 DOM对象:通过document获取的
var oDiv = document.getElementsByTagName("div")[0];
console.log(oDiv);
//2.jquery获取对象 jQuery对象:通过$()获取
console.log($("div"));
-
可以共存不能混用
//3.可以共存,不能混用 oDiv.style.width = "100px"; $("div").css("height",100); //$("div").style.background = "red";
-
相互转换
//4.DOM转jQuery $(DOM); $("div").click(function(){ console.log(this); //DOM $(this).css("background","red"); }); //5.jQuery转DOM $()[下标] $().get(下标) console.log($("div")[0]); console.log($("div").get(0));