jQuery基础操作
JQuery 基础梳理
JQuery 概念: 一个JavaScript框架(简化JS开发)
- jQuery是一个快速、简洁的JavaScript框架,是继Prototype之后又一个优秀的JavaScript代码库(或JavaScript框架)
- jQuery设计的宗旨是“
write Less,Do More”,即倡导写更少的代码,做更多的事情。它封装JavaScript常用的功能代码,提供一种简便的JavaScript设计模式,优化HTML文档操作、事件处理、动画设计和Ajax交互 - JavaScript框架:本质上就是一些js文件,封装了js的原生代码
JQuery 快速入门
1.下载JQuery
- 目前jQuery有三个大版本:
1.x:兼容ie678,使用最为广泛的,官方只做BUG维护- 功能不再新增。因此一般项目来说,使用1.x版本就可以了
- 最终版本:1.12.4 (2016年5月20日)
2.x:不兼容ie678,很少有人使用,官方只做BUG维护- 功能不再新增。如果不考虑兼容低版本的浏览器可以使用2.x
- 最终版本:2.2.4 (2016年5月20日)
3.x:不兼容ie678,只支持最新的浏览器。- 除非特殊要求,一般不会使用3.x版本的,很多老的jQuery插件不支持这个版本,目前该版本是官方主要更新维护的版本。
- 最新版本:3.2.1(2017年3月20日)
- jquery-xxx.js 与 jquery-xxx.min.js区别:
jquery-xxx.js:开发版本。给程序员看的,有良好的缩进和注释。体积大一些jquery-xxx.min.js:生产版本。程序中使用,没有缩进。体积小一些。程序加载更快
2.导入JQuery的js文件:导入xxx.js文件
在body标签内的最底部导入jquery文件,就可以使用jquery里面的方法了。
<script src="../static/jquery-1.12.4.js"></script>
3、首先是需要找到HTML里面的标签,才能对其进行操作。
1.) 基本选择器
标签选择器(元素选择器)
- 语法:
$("html标签名")获得所有匹配标签名称的元素,例如:$("span")
id选择器
语法: $("#id的属性值") 获得与指定id属性值匹配的元素,例如: $("#tb") ,tb是在html中有一个标签定义的id名称叫tb。
类选择器
语法: $(".class的属性值") 获得与指定的class属性值匹配的元素,例如: $(".c1的属性值"),点是固定写法,class是指html中有一个class的名称叫c1。
并集选择器:
语法: $("选择器1, 选择器2...") 获取多个选择器选中的所有元素,$("选择器1, 选择器2..."),例如,$("#tb, .c1..."),中间的逗号就是和的意思。
2.) 层级选择器
- 后代选择器
- 语法:
$("A B ")选择A元素内部的所有B元素(子子孙孙)
儿子选择器
语法: $("A > B") 选择A元素内部的所有B子元素,只有A下面的儿子才被找到。
3.) 属性选择器
- 属性名称选择器
- 语法:
$("A[属性名]")包含指定属性的选择器,例如:$('input[type]'),$('input[type="button"]'),自定义的属性都可以找到,还可以写成$('[test="haha"]')。
属性选择器
语法: $("A[属性名='值']") 包含指定属性等于指定值的选择器,例如:$('input[type="checkbox"]'),相比上面的属性名称选择器更加准确。一定注意单双引号要交叉使用,不能都是单引号,也不能都是双引号。精简写法$(':checkbox')
复合属性选择器
语法: $("A[属性名='值'][...]...") 包含多个属性条件的选择器,例如:$('input[test="haha"][type="checkbox"]'),意思是找一个input标签,标签的属性是test=haha和type等于checkbox,精准定位。
4.) 过滤选择器
首元素选择器
语法: :first 获得选择的元素中的第一个元素
尾元素选择器
语法: :last 获得选择的元素中的最后一个元素
如下图:

等于索引选择器,注意index指定的查找到的元素下标,是从0开始的。
语法: :eq(index) 指定索引元素

大于索引选择器
语法: :gt(index) 大于指定索引元素
小于索引选择器
语法: :lt(index) 小于指定索引元素

JQuery DOM操作
一、内容操作
- 1.)
html():获取/设置元素的标签体内容
<a><font>内容</font></a> --> <font>内容</font>
如下,把整个html都返回回来。
![]()
- 2.)
text():获取/设置元素的标签体纯文本内容
<a><font>内容</font></a> --> 内容
如下,只返回文本内容
![]()
- 3.)
val():获取/设置元素的value属性值

二、属性操作
1.) 通用属性操作
attr():获取/设置元素的属性removeAttr():删除属性prop():获取/设置元素的属性
获取值

设置值

removeProp():删除属性
取消打钩(和
效果是一样的)

- attr和prop区别?
- 如果操作的是元素的固有属性,则建议使用prop
- 如果操作的是元素自定义的属性,则建议使用attr
2.) 对class属性操作
addClass():添加class属性值removeClass():删除class属性值toggleClass():切换class属性,toggle的中文意思是切换,那就是切换class属性了。- toggleClass("one"):
- 判断如果元素对象上存在 class="one",则将属性值one删除掉。
- 如果元素对象上不存在 class="one",则添加
给class=‘c1’下的th标签加上class=‘main’的属性。

3.)设置元素的css样式
$("div").css("width","30px");
$("div").css("height","30px").css("background","red");
$("div").css({"font-size":"30px","color":"red"}); // 同时设置多个样式属性
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>jquerytest</title>
</head>
<body>
<div>
<table border="1">
<div id="choice">
<input type="button" value="全选" onclick="allcheck();">
<input type="button" value="取消" onclick="allcancle();">
<input type="button" value="反选" onclick="reverse();">
</div>
<thead class="c1">
<tr>
<th>选项</th>
<th>主机名</th>
<th>ip地址</th>
</tr>
</thead>
<tbody id="tb">
<tr>
<td><input type="checkbox"></td>
<td><a>1.1.1.1</a></td>
<td><a>人力服务器</a></td>
</tr>
<tr>
<td><input type="checkbox" test="haha"></td>
<td><a>1.1.1.2</a></td>
<td><a>财务服务器</a></td>
</tr>
<tr>
<td><input type="checkbox"></td>
<td><a>1.1.1.3</a></td>
<td><a>运维服务器</a></td>
</tr>
<tr>
<td><input type="checkbox"></td>
<td><a>1.1.1.4</a></td>
<td><a>开发服务器</a></td>
</tr>
<tr>
<td><input type="checkbox"></td>
<td><a>1.1.1.5</a></td>
<td><a>发布服务器</a></td>
</tr>
</tbody>
</table>
</div>
<script src="../static/jquery-1.12.4.js"></script>
<script>
function allcheck(){
$('#tb :checkbox').prop('checked',true)
}
function allcancle(){
$('#tb td :checkbox').prop('checked',false)
}
function reverse(){
$('#tb :checkbox').each(function (){
if(this.checked){
this.checked = false
}else{
this.checked = true
}
})
}
</script>
</body>
</html>
4.)常用筛选器
筛选器
- $(this).next() 下一个
- $(this).prev() 上一个
- $(this).prevAll() 同一级上面的所有
- $(this).parent() 父
- $(this).parents()不常用“多个父级标签”
- $(this).children() 孩子
- $('#i1').siblings() 兄弟
- $('#i1').find('#i1') 子子孙孙中查找
5)文档处理
- append 内部插入
- prepend 内部插入
- after 外部插入
- before 外部插入
- empty 删除标签内部的
6)正则表达式
1、定义正则表达式
- /.../ 用于定义正则表达式
- /.../g 表示全局匹配
- /.../i 表示不区分大小写
- /.../m 表示多行匹配
- JS正则匹配时本身就是支持多行,此处多行匹配只是影响正则表达式^和$,m模式也会使用^$来匹配换行的内容)
var pattern = /^Java\w*/gm; var text = "JavaScript is more fun than \nJavaEE or JavaBeans!"; result = pattern.exec(text) result = pattern.exec(text) result = pattern.exec(text)
注:定义正则表达式也可以 reg= new RegExp()
2、匹配
JavaScript中支持正则表达式,其主要提供了两个功能:
- test(string) 检查字符串中是否和正则匹配
n = 'uui99sdf' reg = /\d+/ reg.test(n) ---> true # 只要正则在字符串中存在就匹配,如果想要开头和结尾匹配的话,就需要在正则前后加 ^和$
- exec(string) 获取正则表达式匹配的内容,如果未匹配,值为null,否则,获取匹配成功的数组。
获取正则表达式匹配的内容,如果未匹配,值为null,否则,获取匹配成功的数组。 非全局模式 获取匹配结果数组,注意:第一个元素是第一个匹配的结果,后面元素是正则子匹配(正则内容分组匹配) var pattern = /\bJava\w*\b/; var text = "JavaScript is more fun than Java or JavaBeans!"; result = pattern.exec(text) var pattern = /\b(Java)\w*\b/; var text = "JavaScript is more fun than Java or JavaBeans!"; result = pattern.exec(text) 全局模式 需要反复调用exec方法,来一个一个获取结果,直到匹配获取结果为null表示获取完毕 var pattern = /\bJava\w*\b/g; var text = "JavaScript is more fun than Java or JavaBeans!"; result = pattern.exec(text) var pattern = /\b(Java)\w*\b/g; var text = "JavaScript is more fun than Java or JavaBeans!"; result = pattern.exec(text)
3、字符串中相关方法
obj.search(regexp) 获取索引位置,搜索整个字符串,返回匹配成功的第一个位置(g模式无效) obj.match(regexp) 获取匹配内容,搜索整个字符串,获取找到第一个匹配内容,如果正则是g模式找到全部 obj.replace(regexp, replacement) 替换匹配替换,正则中有g则替换所有,否则只替换第一个匹配项, $数字:匹配的第n个组内容; $&:当前匹配的内容; $`:位于匹配子串左侧的文本; $':位于匹配子串右侧的文本 $$:直接量$符号
提示 :
1、jquery支持链式编程,意思就是你可以一直点下去,下图中用的是jquery匿名函数。
2、jquery不用像js那样在标签中写入onclick="addclass();"来定义标签,可以直接$('#tb').click(function(){})在大括号中写入你要干什么,其中this代指的就是当前找到的标签,如下:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>jquerytest</title>
<style>
.header {
background-color: green;
color: wheat;
}
.content {
min-height: 10px;
}
.hide {
display: none;
}
</style>
</head>
<body>
<div style="height:400px;width: 200px;border: 5px solid #dddddd">
<div class="item">
<div class="header">标题一</div>
<div id="i1" class="content hide">内容一</div>
<div id="i1" class="content hide">内容一</div>
<div id="i1" class="content hide">内容一</div>
</div>
<div class="item">
<div class="header">标题二</div>
<div class="content hide">内容二</div>
<div class="content hide">内容二</div>
<div class="content hide">内容二</div>
</div>
<div class="item">
<div class="header">标题三</div>
<div class="content hide">内容三</div>
<div class="content hide">内容三</div>
<div class="content hide">内容三</div>
</div>
</div>
<script src="../static/jquery-1.12.4.js"></script>
<script>
$('.header').click(function (){
//常规写法
//$(this).siblings().removeClass('hide');
// $(this).parent().siblings().children('.content').addClass('hide');
//链式写法
$(this).siblings().removeClass('hide').parent().siblings().children('.content').addClass('hide');
})
</script>
</body>
</html>
下列中有两个新方法prevAll(),prev()和each(),前者是找同层上面的标签,prev是上一个,后者是jquery中经常用到的循环。jquery中可以在click事件中包含click事件。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>jquerytest</title>
<style>
.hide {
display: none;
}
.modal {
position: fixed;
top: 50%;
left: 50%;
width: 500px;
height: 400px;
margin-left: -250px;
margin-top: -250px;
background-color: #eeeeee;
z-index: 10;
}
.shadow {
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
opacity: 0.6;
background-color: black;
z-index: 9;
}
#edit, #del,#cancle,#save {
color: blue;
}
</style>
</head>
<body>
<div>
<div>
<input type="button" value="添加">
</div>
<table border="1">
<thead>
<tr>
<th>序号</th>
<th>主机名</th>
<th>ip</th>
<th>端口</th>
<th colspan="2">操作</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="checkbox"></td>
<td target="hostname">docker1</td>
<td target="ipaddr">1.1.1.1</td>
<td target="port">80</td>
<td id="edit">编辑</td>
<td id="del">删除</td>
</tr>
<tr>
<td><input type="checkbox"></td>
<td target="hostname">docker2</td>
<td target="ipaddr">1.1.1.2</td>
<td target="port">80</td>
<td id="edit">编辑</td>
<td id="del">删除</td>
</tr>
<tr>
<td><input type="checkbox"></td>
<td target="hostname">docker3</td>
<td target="ipaddr">1.1.1.3</td>
<td target="port">80</td>
<td id="edit">编辑</td>
<td id="del">删除</td>
</tr>
<tr>
<td><input type="checkbox"></td>
<td target="hostname">docker4</td>
<td target="ipaddr">1.1.1.4</td>
<td target="port">80</td>
<td id="edit">编辑</td>
<td id="del">删除</td>
</tr>
</tbody>
</table>
<div class="shadow hide"></div>
<div class="modal hide">
<div style="margin-left: 50px">
<p>
<label id="hostname">主机名</label>
<input id="hostname" type="text" name="hostname">
</p>
<p>
<label for="idaddr">IP地址</label>
<input id="idaddr" type="text" name="ipaddr">
</p>
<p>
<label id="port">端口</label>
<input id="idport" type="text" name="port">
</p>
<p>
<input type="button" value="取消">
<input type="button" value="确认">
</p>
</div>
</div>
</div>
<script src="../static/jquery-1.12.4.js"></script>
<script>
$('tbody').delegate('#edit','click',function () {
//找到每个字段的text文本
var hostname = $(this).prevAll('[target="hostname"]').text()
var ipaddr = $(this).prevAll('[target="ipaddr"]').text()
var port = $(this).prevAll('[target="port"]').text()
//让当前的tr隐藏
$(this).parent().addClass('hide')
//字符串拼接,把当前位置td里面的text值加到对应的input下的value框中
var temp = '<tr><td><input type="checkbox"></td>' +
'<td><input type="text" value='+ hostname +'></td>' +
'<td><input type="text" value='+ ipaddr +'></td>' +
'<td><input type="text" value='+ port +'></td>' +
'<td id="save">保存</td>' +
'<td id="cancle">取消</td></tr>'
//在原来的tr标签后面,追加一个tr,内容就是temp内容。
$(this).parent().after(temp)
});
//点击编辑框后取消按钮事件
$('tbody').delegate('#cancle','click',function (){
//让当前这个取消按键的这组tr全部隐藏
$(this).parent().addClass('hide')
//让当前标签的上一级的上一个兄弟标签取消隐藏
$(this).parent().prev().removeClass('hide')
});
//点击保存按钮后保存数据
$('tbody').delegate('#save','click',function (){
//拿到需要的input标签里面的数据
var infor = $(this).prevAll().children()
var port = $(infor[0]).val()
var ipaddr = $(infor[1]).val()
var hostname = $(infor[2]).val()
//让当前这个取消按键的这组tr全部隐藏
$(this).parent().addClass('hide')
//找到每个字段的text文本
//td下target等于input框里的hostname值
$(this).parent().prev().children('[target="hostname"]').text(hostname)
//td下target等于input框里的ipaddr值
$(this).parent().prev().children('[target="ipaddr"]').text(ipaddr)
//td下target等于input框里的port值
$(this).parent().prev().children('[target="port"]').text(port)
//让当前标签的上一级的上一个兄弟标签取消隐藏
$(this).parent().prev().removeClass('hide')
});
//弹框中的取消按钮点击后取消遮罩层和弹框层,及清除弹框层input数据
$('input[value="取消"]').click(function () {
$('.modal,.shadow').addClass('hide');
});
//获取确认添加事件
$('.modal input[value="确认"]').click(function () {
var i = $(this).parent().prevAll().children(':text')
var port = $(i[0]).val()
var ip = $(i[1]).val()
var name = $(i[2]).val()
//字符串拼接注意逗号的写法
$('tbody').append('<tr><td><input type="checkbox"></td><td target="hostname">' + name + '</td><td target="ipaddr">' + ip + '</td><td target="port">' + port + '</td><td id="edit">编辑</td><td id="del">删除</td></tr>')
$('.modal,.shadow').addClass('hide');
});
//添加按钮弹出输入框函数,根据索引取到值(这里比较传统,可以参考编辑按钮的新写法),
// 然后再用append方法在tbody标签内最后追加一个tr标签(里面用到了字符串拼接法)。
$('div input[value="添加"]').click(function () {
$('.modal input[type="text"]').val('')
$('.modal,.shadow').removeClass('hide')
});
//删除按钮
$('tbody').delegate('#del','click',function () {
$(this).parent().remove()
});
</script>
</body>
</html>
添加,编辑,删除,模态对话框健全版
tag示例,效果如下图:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>jquerytest</title>
<style>
.hide {
display: none;
}
.menu {
height: 38px;
line-height: 38px;
border-bottom:1px solid red;
}
.active {
background-color: darkgray;
}
.menu .menu-item {
float: left;
border-right: 1px solid #eeeeee;
padding: 0 10px;
cursor: pointer;
}
.content {
min-height: 100px;
height: 500px;
border: 1px solid #9e9e9e;
border-top: none;
}
</style>
</head>
<body>
<div style="width: 700px;margin:0 auto">
<div class="menu">
<div class="menu-item active" a="1">菜单一</div>
<div class="menu-item" a="2">菜单二</div>
<div class="menu-item" a="3">菜单三</div>
</div>
<div class="content">
<div b="1">内容一</div>
<div class="hide" b="2">内容二</div>
<div class="hide" b="3">内容三</div>
</div>
</div>
<script src="../static/jquery-1.12.4.js"></script>
<script>
$('.menu-item').click(function () {
$(this).addClass('active').siblings().removeClass('active');
var target = $(this).attr('a');
$('.content').children("[b='" + target + "']").removeClass('hide').siblings().addClass('hide');
});
</script>
</body>
</html>

DOM: 三种绑定方式
jQuery:
第一种最常见的:
$('.c1').click()
$('.c1').....
第二种bind方式,有绑定和解绑的方式,表现和第一种一样。
$('.c1').bind('click',function(){
})
$('.c1').unbind('click',function(){
})
*******************
第三种事件委托delegate了不得,用它绑定的事件不用刷新,就能自动应用上这个方法的事件。比如,默认编辑框是有个模态对话框的事件,点击后就自动弹窗,如果用其他方法绑定事件的话是不会自动绑定这个编辑框的事件,用delegatre的话完成后就会自动绑定这个编辑按钮的事件。
具体可以看前面编辑框操作中的操作按钮事件。注意点c和后面a的形式是,class=‘c’下面子子孙孙的a标签。其目的jQuery的事件绑定是在页面加载完毕之后,找到相关标签并为其绑定事件,如果后期通过js代码有新增表现,那么新标签中模式是没有事件的。
$('.c').delegate('a', 'click', function(){
})
$('.c').undelegate('a', 'click', function(){
})
第四种绑定和解绑的方式是最原始的,据说归根结底前面三种用的方式原始操作都是下面这种。
$('.c1').on('click', function(){
})
$('.c1').off('click', function(){
})
标签绑定事件的return问题
如下:a标签点击以后不是直接跳转,而是alert一下,如果这里写的return是true就跳转,false就不会跳转到href的地址,注意的是onclick事件名称前面一定要加上return。而其他标签则不需要在onclick里面写上return,直接在方法里写上return的是true还是false。
<a onclick="return a_event()" href="https://www.baidu.com">百度首页</a>
<span onclick="span_event()">百度地图</span>
<script src="../static/jquery-1.12.4.js"></script>
<script>
function a_event(){
alert("确认")
return true
};
function span_event(){
alert("确认")
return true
};
</script>
自动执行函数和普通函数区别
//当页面框架加载完毕后自动执行函数,只要框架加载完成后,不管元素的加载进度,直接执行这种函数。
$(function (){
alert('test1')
})
//当页面查找的标签元素加载完毕后执行,这里的执行不是用鼠标的执行,是给这个元素应用上这个事件,如果ima标签或其他标签元素卡主了,就执行不到这里,相反如果是前者就不会卡住。
$('a').click(function (){
alert('test2')
})
form表单的简单验证
验证长度和必填事项
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
.error{
color: red;
}
</style>
</head>
<body>
<form id="f1" action="s5.html" method="POST">
<div><input name="n1" tex = "用户名" type="text" /></div>
<div><input name="n2" tex = "密码" type="password" /></div>
<div><input name="n3" tex = "邮箱" type="text" /></div>
<div><input name="n4" tex = "端口" type="text" /></div>
<div><input name="n5" tex = "IP" type="text" /></div>
<input type="submit" value="提交" />
<!--<img src="...">-->
</form>
<script src="jquery-1.12.4.js"></script>
<script>
// 当页面框架加载完毕后,自动执行
// $(function(){
// $.Login('#f1')
// });
$(function(){
// 当页面所有元素完全加载完毕后,执行
$(':submit').click(function () {
//点击提交以后先把有class=‘error’属性的标签删除。
$('.error').remove();
//设置一个变量。
var flag = true;
//找到id等于f1下的所有input等于text和password属性的标签,然后循环每个标签。
$('#f1').find('input[type="text"],input[type="password"]').each(function () {
//找到这个标签的value值
var v = $(this).val();
//找到这个标签的属性tex的值
var n = $(this).attr('tex');
//判断,如果这个标签的value长度小于等于0,就执行if里面的操作。
if(v.length <= 0){
//把前面的flag变量先改成false,让页面不要跳转。
flag = false;
//新建一个span标签。
var tag = document.createElement('span');
//span标签加上class=‘error’,这样字体就是红色了。
tag.className = "error";
//把tex属性值加上必填两个字
tag.innerHTML = n + "必填";
//然后再这个input标签后面把做好的span加进去。
$(this).after(tag);
return false;
}
});
//如果返回的是false就不执行跳转
return flag;
});
});
//简单的长度判断验证
// $(':submit').click(function () {
// var v = $(this).prev().val();
// if(v.length > 0){
// return true;
// }else{
// alert('请输入内容');
// return false
// }
// })
</script>
</body>
</html>
jquery扩展方法
下面是简单写法,如果想自定义方法的话,可以这么定义和应用。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div id="i1">准备弹窗</div>
<script src="../static/jquery-1.12.4.js"></script>
<script>
// jquery扩展一:
//定义写法
$.fn.extend({
"zhangsan": function () {
return 'zhangsan function';
}
});
//执行方法,必须的找到一个元素然后点才能执行。
var v = $('#i1').zhangsan();
alert(v);
// jquery扩展二:
//定义写法
$.extend({
'lisi': function () {
return 'lisi function';
}
});
//执行方法,直接$符点方法就能执行。
var v = $.lisi();
alert(v);
</script>
</body>
</html>
前端后端架构等其它详情请参考老男孩网站:https://pythonav.com/wiki/detail/5/64/
js其它基本操作可参考:https://www.cnblogs.com/wupeiqi/articles/5602773.html
具体参数可以参考:
1、https://jquery.cuishifeng.cn/
2、https://www.w3school.com.cn/jquery/jquery_install.asp
3、https://zhuanlan.zhihu.com/p/292288287



浙公网安备 33010602011771号