前面学习了原生的DOM,现在看看如何使用JQuery。JQuery建议使用1.12的版本,这样对旧版本的IE兼容性比较好。
例1.添加,删除class
知识要点:
1. 通过<script src='jquery-1.12.4.js></script>调用jquery
2. 相对于Dom的document.getElementbyID('i1'), JQuery直接使用$('#i1');
类似的,查找类可以用$('.c1'),查找p标签 $('p'),查找form的元素 $(':text') ,还可以组合使用。具体的选择器可以参考https://www.w3schools.com/jquery/jquery_ref_selectors.asp
3. addclass(‘hide’)直接给找到的标签添加一个样式class,removeClass('hide')删除一个class,无需使用classlist了
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<style>
.hide{
display: none;
}
</style>
</head>
<body>
<input type="button" value="hide" onclick="hides();"/>
<div id="i1">
<div class="item"></div>
<div class="item">
<div class="c1">123</div>
<a>百度</a>
</div>
<div class="item"></div>
</div>
<div id="i2"></div>
<script src="jquery-1.12.4.js"></script>
<script>
flag=true;
function hides() {
if (flag==true){
$('#i1').addClass('hide');
console.log(flag)
flag=false;
}else{
$('#i1').removeClass('hide');
console.log(flag)
flag=true;
}
}
</script>
</body>
</html>
点击hide按钮切换隐藏效果
例2. 全选和反选
这个例子在前面的Dom里面出现过,现在看看JQuery如何实现
知识点:
1. 选择器可以组合使用 比如 $('#tb :checkbox') 表示id=tb下面所有的checkbox元素
2. 对于checkbox的属性,通过prop()来实现,如果是自定义的其他的属性,通过attr()实现
3. each()可以实现循环,循环里面如果输出this,可以看见他是一个dom的格式,如果把他转换成jquery对象的格式(数组格式),可以通过$(this)实现,如果想把jquery转为dom的格式,那么直接取第一个数组的值就行了,例子里面实现了3种方式,dom,jquery以及三元运算符的格式
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<input type="button" value="全选" onclick="checkAll();" />
<input type="button" value="反选" onclick="reverseAll();" />
<input type="button" value="取消" onclick="cancleAll();"/>
<table border="1">
<thead>
<tr>
<th>选项</th>
<th>IP</th>
<th>PORT</th>
</tr>
</thead>
<tbody id="tb">
<tr>
<td><input type="checkbox" /></td>
<td>1.1.1.1</td>
<td>80</td>
</tr>
<tr>
<td><input type="checkbox" /></td>
<td>1.1.1.1</td>
<td>80</td>
</tr>
<tr>
<td><input type="checkbox" /></td>
<td>1.1.1.1</td>
<td>80</td>
</tr>
</tbody>
</table>
<script src="jquery-1.12.4.js"></script>
<script>
function checkAll() {
$('#tb :checkbox').prop('checked',true);
}
function cancleAll() {
$('#tb :checkbox').prop('checked',false);
}
function reverseAll() {
$(':checkbox').each(function(k){
// this,代指当前循环的每一个元素
// Dom
/*
if(this.checked){
this.checked = false;
}else{
this.checked = true;
}
*/
/*
if($(this).prop('checked')){
$(this).prop('checked', false);
}else{
$(this).prop('checked', true);
}
*/
// 三元运算var v = 条件? 真值:假值
var v = $(this).prop('checked')?false:true;
$(this).prop('checked',v);
})
}
</script>
</body>
</html>
例3 隐藏菜单
知识点:
1. click的事件可以直接选择到标签之后执行,这个比在html里面使用onclick事件要好很多。
2. Jquery支持链式的编程,因此如下所示可以一行实现很多功能
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
.header{
background-color: black;
color: wheat;
}
.content{
min-height: 50px;
}
.hide{
display: none;
}
</style>
</head>
<body>
<div >
<div class="item">
<div class="header">标题一</div>
<div id="i1" class="content hide">内容</div>
</div>
<div class="item">
<div class="header">标题二</div>
<div class="content hide">内容</div>
</div>
<div class="item">
<div class="header">标题三</div>
<div class="content hide">内容</div>
</div>
</div>
<script src="jquery-1.12.4.js"></script>
<script>
$('.header').click(function(){
$(this).next().removeClass('hide').parent().siblings().find('.content').addClass('hide')
})
</script>
</body>
</html>
例4. 复制,删除文本框
clone()克隆标签
find()查找标签
attr()添加一个事件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<div>
<p>
<a onclick="Add(this);"> + </a>
<input type="text" />
</p>
</div>
<script src="jquery-1.12.4.js"></script>
<script>
function Add(ths){
var p = $(ths).parent().clone();
p.find('a').text(' - ');
p.find('a').attr('onclick', 'Remove(this);');
$(ths).parent().parent().append(p);
}
function Remove(ths){
$(ths).parent().remove();
}
</script>
</body>
</html>
效果:点击+自动复制一行,点击-删除自己所在
例5. 绑定事件-例2的升级版
例2里面我们需要给每个标签都手动的添加onclick事件,如果可以统一绑定事件,会省事很多。有两种方式,如下所示;
$(function){
....
}里面执行的...会在文档树加载之后自动执行,不会等待所有的图片内容的加载
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<style>
.hide{
display: none;
}
.menu{
width: 200px;
height: 600px;
border: 1px solid #dddddd;
overflow: auto;
}
.menu .item .title{
height: 40px;
line-height: 40px;
background-color: #2459a2;
color: white;
}
</style>
</head>
<body>
<div class="menu">
<div class="item">
<div class="title">菜单一</div>
<div class="body">
<p>内容一</p>
<p>内容一</p>
<p>内容一</p>
<p>内容一</p>
<p>内容一</p>
</div>
</div>
<div class="item">
<div class="title" >菜单二</div>
<div class="body hide">
<p>内容二</p>
<p>内容二</p>
<p>内容二</p>
<p>内容二</p>
<p>内容二</p>
<p>内容二</p>
</div>
</div>
<div class="item">
<div class="title">菜单三</div>
<div class="body hide">
<p>内容三</p>
<p>内容三</p>
<p>内容三</p>
<p>内容三</p>
<p>内容三</p>
<p>内容三</p>
</div>
</div>
</div>
<script src="jquery-1.12.4.js"></script>
<script>
//方法一
// $(function(){
// // 当文档树加载完毕后,自动执行
// $('.item .title').click(function(){
// // this,$(this)
// $(this).next().removeClass('hide');
// $(this).parent().siblings().find('.body').addClass('hide');
// });
// });
//方法二
$('.item .title').bind('focus', function () {
$(this).next().removeClass('hide');
$(this).parent().siblings().find('.body').addClass('hide');
})
</script>
</body>
</html>
例6 事件的延迟绑定
比如通过javascript创建的新标签,如何让他自动绑定事件?可以通过delegate实现
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<input type="button" onclick="Add();" />
<ul>
<li>123</li>
<li>456</li>
<li>789</li>
</ul>
<script src="jquery-1.12.4.js"></script>
<script>
$(function(){
/*
$('li').click(function () {
alert($(this).text());
});
*/
$("ul").delegate("li","click",function(){
alert($(this).text());
});
});
function Add(){
var tag = document.createElement('li');
tag.innerText = '666';
$('ul').append(tag);
}
</script>
</body>
</html>
例7 模态对话框 (高级版)
之前用DOM实现过模态对话框,现在用JQuery实现同样的功能。
知识要点:
1.模态对话框的HTML和CSS布局,3层,最上层居中,中间一个阴影层,最下面是主界面,上面两层默认隐藏,通过z-index区分上下顺序
2. 可以通过attr()方法来获取和设置自定义的属性;如果是checkbox或者radio,那么通过prop()方法来获取和设定属性
3.通过属性来定位元素,比如 $("[editable='false']")则可以获取editable属性为false的那个标签元素
4. 文本编辑,对于InnerText的值是通过text()实现,对于input的表单内容则是通过val()实现
5. 添加class,删除class通过addClass()和removeClass()实现
6. delegate 延迟绑定的实现,一般用于未来的新的标签,比如通过脚本创建的标签
7. 动态的创建标签,可以直接插入html字符串或者通过CreateElement()实现
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</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;
}
.item{
position: relative;
width: 100px;
margin-top: 20px;
margin-left: 30px;
}
.label{
width: 40px;
color: chocolate;
}
.content{
width:100px;
position: absolute;
right:-80px;
}
.buttons{
margin-top: 20px;
margin-left: 30px;
}
</style>
</head>
<body>
<a onclick="addElement();">添加</a>
<table border="1" id="tb">
<tr>
<td target="hostname">1.1.1.11</td>
<td target="port">80</td>
<td target="ip">80</td>
<td editable="true">
<a class="edit" >编辑</a> | <a class="del">删除</a>
</td>
</tr>
<tr>
<td target="hostname">1.1.1.12</td>
<td target="port">80</td>
<td target="ip">80</td>
<td editable="true">
<a class="edit">编辑</a> | <a class="del">删除</a>
</td>
</tr>
<tr>
<td target="hostname">1.1.1.13</td>
<td target="port">80</td>
<td target="ip">80</td>
<td editable="true">
<a class="edit">编辑</a> | <a class="del">删除</a>
</td>
</tr>
<tr>
<td target="hostname">1.1.1.14</td>
<td target="port">80</td>
<td target="ip">80</td>
<td editable="true">
<a class="edit">编辑</a> | <a class="del">删除</a>
</td>
</tr>
</table>
<div class="modal hide">
<div >
<div class="item">
<label class="label">主机名</label>
<input class="content" name="hostname" type="text" />
</div>
<div class="item">
<label class="label">端口</label>
<input class="content" name="port" type="text" />
</div>
<div class="item">
<label class="label">IP地址</label>
<input class="content" name="ip" type="text" />
</div>
</div>
<div class="buttons">
<input type="button" value="取消" onclick="cancelModal();" />
<input type="button" value="添加" onclick="addModal();" />
<input type="button" value="修改" onclick="updateModal();" />
</div>
</div>
<div class="shadow hide"></div>
<script src="jquery-1.12.4.js"></script>
<script>
$("#tb").delegate('.del',"click",function () {
$(this).parent().parent().remove();
})
function addModal() {
var tr = document.createElement('tr');
var td1 = document.createElement('td');
td1.innerHTML = $(".modal input[name='hostname']").val();
var att1=document.createAttribute('target');
att1.value='hostname';
td1.setAttributeNode(att1);
var td2 = document.createElement('td');
td2.innerHTML = $(".modal input[name='port']").val();
var att2=document.createAttribute('target');
att2.value='port';
td2.setAttributeNode(att2);
var td3 = document.createElement('td');
td3.innerHTML = $(".modal input[name='ip']").val();;
var att3=document.createAttribute('target');
att3.value='ip';
td3.setAttributeNode(att3);
var td4 = document.createElement('td');
td4.innerHTML = " <a class='edit'>编辑</a> | <a class='del'>删除</a>"
$(tr).append(td1);
$(tr).append(td2);
$(tr).append(td3);
$(tr).append(td4);
$('#tb').append(tr);
$(".modal,.shadow").addClass('hide');
}
function addElement() {
$(".modal,.shadow").removeClass('hide');
}
function cancelModal() {
$(".modal,.shadow").addClass('hide');
$('.modal input[type="text"]').val("");
}
function updateModal(){
var host=$(".modal input[name='hostname']").val()
var port=$(".modal input[name='port']").val()
var ip=$(".modal input[name='ip']").val()
var tds=$("[editable='false']").prevAll()
console.log(tds)
tds.each(
function () {
console.log($(this).attr('target'))
if($(this).attr('target')=='ip'){
$(this).text(ip);
console.log('update ip')
}
else if($(this).attr('target')=='port'){
$(this).text(port);
console.log('update port')
}
else if($(this).attr('target')=='hostname'){
$(this).text(host)
console.log('update host')
}
}
)
$(".modal,.shadow").addClass('hide');
$("[editable='false']").attr('editable','true')
}
$("#tb").delegate(".edit","click",function() {
$(".modal,.shadow").removeClass('hide');
// this
$(this).parent().attr('editable', 'false')
var tds = $(this).parent().prevAll();
tds.each(function () {
// 获取td的target属性值
var n = $(this).attr('target');
// 获取td中的内容
var text = $(this).text();
var a1 = '.modal input[name="';
var a2 = '"]';
var temp = a1 + n + a2;
$(temp).val(text);
})
})
</script>
</body>
</html>
例8 TAB效果
知识点:
1.AddClass和RemoveClass的使用
2.小技巧,通过自定义的属性值进行匹配,定位标签的时候因为格式为[attr=‘value’]的格式,因此做了一个字符串的拼接
3.注释掉的代码是另外一种方法,可以通过索引来进行匹配
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
.hide{
display: none;
}
.menu{
height: 38px;
background-color: #eeeeee;
line-height: 38px;
}
.active{
background-color: brown;
}
.menu .menu-item{
float: left;
border-right: 1px solid red;
padding: 0 5px;
cursor: pointer;
}
.content{
min-height: 100px;
border: 1px solid #eeeeee;
}
</style>
</head>
<body>
<div >
<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="jquery-1.12.4.js"></script>
<script>
$('.menu-item').click(function(){
$(this).addClass('active').siblings().removeClass('active');
var target = $(this).attr('a');
# $('.content').children().eq($(this).index()).removeClass('hide').siblings().addClass('hide');
$('.content').children("[b='"+ target+"']").removeClass('hide').siblings().addClass('hide');
});
</script>
</body>
</html>
例9 点赞
知识点:
1. Jquery里面通过css()来改变一个标签的style
2. 思路和Dom一样的,动态创建一个span标签,通过定时器改变大小和位置,当透明度低于一定程度,结束定时器
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
.container{
padding: 50px;
border: 1px solid #dddddd;
}
.item{
position: relative;
width: 30px;
}
</style>
</head>
<body>
<div class="container">
<div class="item">
<span>赞</span>
</div>
</div>
<div class="container">
<div class="item">
<span>赞</span>
</div>
</div>
<div class="container">
<div class="item">
<span>赞</span>
</div>
</div>
<div class="container">
<div class="item">
<span>赞</span>
</div>
</div>
<script src="jquery-1.12.4.js"></script>
<script>
$('.item').click(function () {
AddFavor(this);
});
function AddFavor(self) {
// DOM对象
var fontSize = 15;
var top = 0;
var right = 0;
var opacity = 1;
var tag = document.createElement('span');
$(tag).text('+1');
$(tag).css('color','green');
$(tag).css('position','absolute');
$(tag).css('fontSize',fontSize + "px");
$(tag).css('right',right + "px");
$(tag).css('top',top + 'px');
$(tag).css('opacity',opacity);
$(self).append(tag);
var obj = setInterval(function () {
fontSize = fontSize + 10;
top = top - 10;
right = right - 10;
opacity = opacity - 0.1;
$(tag).css('fontSize',fontSize + "px");
$(tag).css('right',right + "px");
$(tag).css('top',top + 'px');
$(tag).css('opacity',opacity);
if(opacity < 0){
clearInterval(obj);
$(tag).remove();
}
}, 40);
}
</script>
</body>
</html>
例10 鼠标移动窗口
下面这个例子可以通过鼠标拖曳窗口
知识点:
1. offset()显示的是当前标签在整个html里面的坐标,还有一个position()显示的是在absolute在relative标签里面的位置
2. event=e || windows.event 是为了兼容旧版的IE来获取当前的事件, _event.clientX和_event.clientY这里获取的是鼠标的坐标
3. 绑定事件有几种方式,比如直接通过标签执行 $(''#title).mousover(function(){}); 或者通过on绑定,off接触绑定,例如$(''#title).on('mousemove',function(){}), $(''#title).off('mousemove'); 或者可以通bind和unbind绑定和接触绑定,比如例5;最后还可以通过delegate()来延迟绑定,比如例6
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
</head>
<body>
<div >
<div id="title" ></div>
<div ></div>
</div>
<script type="text/javascript" src="jquery-1.12.4.js"></script>
<script>
$(function(){
//鼠标放在标签上面自动变成移动的符号
$('#title').mouseover(function(){
$(this).css('cursor','move');
});
//鼠标单击的事件
$("#title").mousedown(function(e){
console.log($(this).offset());
//鼠标所在的坐标
var _event = e || window.event;
var ord_x = _event.clientX;
var ord_y = _event.clientY;
console.log(ord_x)
console.log(ord_y)
//标签左上角在html里面的坐标
var parent_left = $(this).parent().offset().left;
var parent_top = $(this).parent().offset().top;
$('#title').on('mousemove', function(e){
var _new_event = e || window.event;
var new_x = _new_event.clientX;
var new_y = _new_event.clientY;
//获取标签左上角的新坐标
var x = parent_left + (new_x - ord_x);
var y = parent_top + (new_y - ord_y);
$(this).parent().css('left',x+'px');
$(this).parent().css('top',y+'px');
})
});
$("#title").mouseup(function(){
//撤销绑定事件
$("#title").off('mousemove');
});
})
</script>
</body>
</html>
例11 阻止事件的发生
有的时候,我们会希望根据一定的条件阻止某个事件的发生,比如表单验证,如果不符合格式或者内容,则无法提交。
知识点:
默认情况下,当我们执行了自定义的Click事件后,他会自动跳转到href指定的地址。但是如果我们把自定义的事件返回值为false,那么他就不会执行后面的操作
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<a onclick="return ClickOn()" href="http://www.oldboyedu.com">走你1</a>
<a id="i1" href="http://www.oldboyedu.com">走你2</a>
<script src="jquery-1.12.4.js"></script>
<script>
function ClickOn() {
alert(123);
return false;
}
$('#i1').click(function () {
alert(456);
return false;
})
</script>
</body>
</html>
例12 JQuery的扩展事件
如果希望自己定义一个事件,然后让JQuery来调用的,可以通过extend
知识点:
1. extend的使用有两种方式:$. extend('name':function(){})定义,然后$.name来调用; 或者是$.fn.extend()定义,然后通过$('#id').name的方式来调用
2. 可以把这些扩展方法都写入一个专门的js文件,注意在plugin文件里面,我们是把他放在了一个自执行的方法里面,这个是为了避免和其他js文件里面变量名的冲突。这里我可以直接把JQuery作为参数传进去,这样arg.extend 就相当于$.extend了
plugin1.js
(function (arg) {
var status = 1;
arg.extend({
'Hellow': function () {
return 'HOHOH';
}
});
})(jQuery);
test.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<script src="jquery-1.12.4.js"></script>
<script src="plugin2.js"></script>
<script>
var v = $.Hellow();
alert(v);
</script>
</body>
</html>
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。