1 初识jQury
1.1 环境搭建
jQuery是一个JavaScript脚本库,不需要特别的安装,只需要我们在页面 <head> 标签内中,通过 script 标签引入 jQuery 库即可。
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript" src="https://www.imooc.com/static/lib/jquery/1.9.1/jquery.js"></script>
或者
<script src="jQuery-1.12.4.js"></script>
<title>环境搭建</title>
</head>
1.2 jQueryHelloWorld体验
当页面加载完成后,在页面中以居中的方式显示“您好!通过慕课网学习 jQuery 才是最佳的途径”字样。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>第一个简单的jQuery程序</title>
<style type="text/css">
div{
padding:8px 0px;
font-size:12px;
text-align:center;
border:1px solid #888;
}
</style>
<script src="https://www.imooc.com/static/lib/jquery/1.9.1/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("div").html("您好!通过慕课网学习jQuery才是最佳的途径。");
});
</script>
</head>
<body>
<div></div>
</body>
</html>
代码分析:
$(document).ready 的作用是等页面的文档(document)中的节点都加载完毕后,再执行后续的代码,因为我们在执行代码的时候,可能会依赖页面的某一个元素,我们要确保这个元素真正的的被加载完毕后才能正确的使用。
2 jQuery选择器
2.1 id选择器
id选择器:一个用来查找的ID,即元素的id属性
$( "#id" )
jQuery内部使用JavaScript函数document.getElementById()来处理ID的获取。
2.2 类选择器
类选择器,顾名思义,通过class样式类名来获取节点
$( ".class" )
jQuery使用JavaScript的原生getElementsByClassName()函数来实现的
2.3 元素选择器
元素选择器:根据给定(html)标记名称选择所有的元素
$( "element" )
搜索指定元素标签名的所有节点,这个是一个合集的操作。同样的也有原生方法getElementsByTagName()函数支持
2.4 全选择器
在CSS中,经常会在第一行写下这样一段样式
* {padding: 0; margin: 0;}
通配符意味着给所有的元素设置默认的边距。jQuery中我们也可以通过传递选择器来选中文档页面中的元素
描述:
$( "*" )
抛开jQuery,如果要获取文档中所有的元素,通过document.getElementsByTagName()中传递"*"同样可以获取到
2.5 层级选择器

$('div > p')
$('div p')
$(".prev + div")
$(".prev ~ div")
2.6 基本筛选选择器

$(".div:first")
$(".div:last")
$(".div:even")
$(".div:odd")
$(".aaron:eq(2)")
$(".aaron:gt(3)")
$(".aaron:lt(2)")
$("input:not(:checked) + p")
2.7 内容筛选选择器

$(".div:contains(':contains')")
$(".div:has(span)")
$("a:parent")
$("a:empty")
2.8 可见性筛选选择器

$('#div1:visible')
$('#div2:visible')
$('#div3:visible')
$('#div1:hidden')
$('#div2:hidden')
$('#div3:hidden')
2.9 属性筛选选择器

$('div[name=p1]')
$('div[p2]')
$('div[name|="-"]')
$('div[name~="a"]')
$('div[name^=imooc]')
$('div[name$=imooc]')
$('div[name*="test"]')
$('div[testattr!="true"]')
2.10 子元素筛选选择器

$('.first-div a:first-child')
$('.first-div a:last-child')
$('.first-div a:only-child')
$('.last-div a:nth-child(2)')
$('.last-div a:nth-last-child(2)')
2.11 表单元素选择器

$(':input')
$('input:text')
$('input:password')
$('input:radio')
$('input:checkbox')
$('input:submit')
$('input:image')
$('input:button')
$('input:file')
2.12表单对象属性筛选选择器

$('input:enabled')
$('input:disabled')
$('input:checked')
$('option:selected')
2.13 特殊选择器this
$('p').click(function(){
//把p元素转化成jQuery的对象
var $this= $(this)
$this.css('color','red')
})
网友评论