jQuery基础语法-查找标签
查找标签
$(selector).action()
选择器
id选择器:
$("#id")
标签选择器:
$("tagName")
class选择器:
$(".className")
配合使用:
$("div.c1") // 找到有c1 class类的div标签
所有元素选择器:
$("*")
组合选择器:
$("#id, .className, tagName")
层级选择器:
x和y可以为任意选择器
$("x y");// x的所有后代y(子子孙孙)
$("x > y");// x的所有儿子y(儿子)
$("x + y")// 找到所有紧挨在x后面的y
$("x ~ y")// x之后所有的兄弟y
基本筛选器:
:first // 第一个 :last // 最后一个 :eq(index)// 索引等于index的那个元素 :even // 匹配所有索引值为偶数的元素,从 0 开始计数 :odd // 匹配所有索引值为奇数的元素,从 0 开始计数 :gt(index)// 匹配所有大于给定索引值的元素 :lt(index)// 匹配所有小于给定索引值的元素 :not(元素选择器)// 移除所有满足not条件的标签 :has(元素选择器)// 选取所有包含一个或多个标签在其内的标签(指的是从后代元素找)
例子:
$("div:has(h1)")// 找到所有后代中有h1标签的div标签
$("div:has(.c1)")// 找到所有后代中有c1样式类的div标签
$("li:not(.c1)")// 找到所有不包含c1样式类的li标签
$("li:not(:has(a))")// 找到所有后代中不含a标签的li标签
练习:
自定义模态框,使用jQuery实现弹出和隐藏功能。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
.cover {
position: fixed;
left: 0;
right: 0;
top: 0;
bottom: 0;
background-color: darkgrey;
opacity: 0.8;
z-index: 999;
}
.model {
width: 400px;
height: 200px;
background-color: white;
position: fixed;
left: 50%;
top: 50%;
margin-left: -200px;
margin-top: -100px;
z-index: 1000;
}
.model p{
width: 250px;
margin:20px auto;
font-size: 20px;
}
.model .inp{
border:1px solid #19D5E5;
padding: 10px;
outline: 0;
}
.model #i3{
display: block;
width: 60px;
margin: 10px auto;
border:1px solid #fff;
border-radius: 10%;
outline: 0;
padding: 10px;
cursor: pointer;
}
.hide {
display: none;
}
</style>
</head>
<body>
<input type="button" value="弹" id="i0">
<div class="cover hide"></div>
<div class="model hide">
<p>
<label for="i1">姓名</label>
<input class="inp" id="i1" type="text">
</p>
<p>
<label for="i2">爱好</label>
<input class="inp" id="i2" type="text">
</p>
<input type="button" id="i3" value="关闭">
</div>
<script src="jquery.min.js"></script>
<script>
var tButton = $("#i0")[0];
tButton.onclick = function(){
var coverEle = $(".cover")[0];
var modelEle = $(".model")[0];
$(coverEle).removeClass('hide');
$(modelEle).removeClass('hide');
}
var cButton = $("#i3")[0];
cButton.onclick = function(){
var coverEle = $(".cover")[0];
var modelEle = $(".model")[0];
$(coverEle).addClass('hide');
$(modelEle).addClass('hide');
}
</script>
</body>
</html>
属性选择器:
[attribute] [attribute=value]// 属性等于 [attribute!=value]// 属性不等于
例子:
// 示例
<input type="text">
<input type="password">
<input type="checkbox">
$("input[type='checkbox']");// 取到checkbox类型的input标签
$("input[type!='text']");// 取到类型不是text的input标签
表单常用筛选:
:text :password :file :radio :checkbox :submit :reset :button
例子:
$(":checkbox") // 找到所有的checkbox
表单对象属性:
:enabled :disabled :checked :selected
例子:
<form>
<input name="email" disabled="disabled" />
<input name="id" />
</form>
$("input:enabled") // 找到可用的input标签
<select id="s1">
<option value="beijing">北京市</option>
<option value="shanghai">上海市</option>
<option selected value="guangzhou">广州市</option>
<option value="shenzhen">深圳市</option>
</select>
$(":selected") // 找到所有被选中的option
浙公网安备 33010602011771号