Web之JQuery用法和小例子

jQuery中文文档:https://jquery.cuishifeng.cn/

一、jQuery

1、二者可以相互转换
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

    <div id="i1">123</div>

    <script src="jquery-1.12.4.js"></script>
    <script>
        $("#i1")[0]
        document.getElementById('i1')
    </script>
</body>
</html>

--------
jquery对象[0] ==> dom对象
$(dom对象) ==> jqery对象
2、选择器
1、id		$('#id')
2class	$('.c1')
3、标签		$('a')
4、组合
	<div id='i1' class='i2'>
	<a>ada</a>
	</div>
			$('a,#i1,.i2')
5、层级选择器,找某个标签里面的某个标签
			$('#i1 a')	找到id=i1层级下的a标签,子子孙孙
			$('#i1>a')	找到id=i1层级下的a标签,只找儿子
6、基本选择器
			$('a:first')	找到a标签里的第一个
			$('a:last')		找到a标签里的最后一个
			$('a:even')		找到a标签里的奇数行,即索引值的第0,2,4...$('a:odd')		找到a标签里的偶数行,即索引值的第1,3,5...$('a:eq(1)')	找到a标签里的索引为1的行,即第二行
7、属性选择器
	<div lishang="xiaomeng"></div>
	<div lishang="kaixin"></div>
			$('[lishang]')				找到具有lishang这个属性的标签
			$('[lishang="xiaomeng"]')	找到lishang=xiaomeng的标签	
3、筛选器
$('#li').next()				找到当前标签的下一个同辈标签
$('#li').nextAll()			找到匹配的标签下所有的同辈标签
$('#li').nextUntil('.i1')	找到id为'li'下直到class'i1'的全部同辈标签
$('#li').prev()				找到当前标签的上一个同辈标签
$('#li').prevAll()			找到当前标签的前面的所有同辈标签
$('#li').prevUntil('.i1')	找到当前标签的前面的所有同辈标签直到样式'i1'
$('#li').parent()			找到当前标签的父标签
$('#li').parents()			找匹配标签的全部父类直到祖宗
$('#li').parentsUntil('#i1')往上找祖宗直到id='i1'
$('#li').children()			找到当前标签的孩子标签
$('#li').siblings()			找到当前标签的兄弟标签
$('#li').find('.co')		找当前标签下子子孙孙中class'co'的标签
$('#li').eq(n)				找到当前标签的第n+1个标签
$('#li').first()			找到匹配的第一个元素
$('#li').last()				找到匹配的最后一个元素
$('#li').hasClass('.i1')	是否有'i1'这个样式的标签
4、样式操作篇
$(this).addclass('c1 c2')		给当前标签加上'c1''c2'两条class属性
$(this).removeClass('c3')		给当前标签删掉'c1'这条class属性
$('.c1').toggleClass('hide');	样式为'c1'的标签若有hide样式就去掉,否则加上
$(tag).css('color')				获取匹配标签的颜色
$(tag).css('color','red')		设置匹配标签样式中颜色改为红色
$(tag).css('fontSize','15' + 'px');	设置各种属性,大小
$(tag).css('top','0' + 'px');	距顶部大小
$(tag).css('right','0' + 'px');	距右侧大小
$(tag).css('opacity','1');		透明度
位置
$('window').scrollTop()			获取整个页面窗口当前滑轮的上下位置
$('window').scrollTop(0)		回到顶部
$('window').scrollLeft()		获取整个页面窗口当前滑轮的左右位置
$('window').scrollLeft(0)		回到最左端
$('#i3').offset()				获取匹配标签的坐标
$('#i3').offset().top			获取匹配标签的纵坐标
$('#i3').offset().left			获取匹配标签的横坐标
$('#i3').position()				获得标签相对于父标签(relative)的坐标
$('#i3').height()				获取标签的纯高度
$('#i3').innerHeight()			获取边框 + 纯高度?
$('#i3').outerHeight()			获取边框 + 纯高度?
$('#i3').outerHeight(true)		获取边框 + 纯高度?
5、属性操作
<input id="i1" type="button" value="开关">

$('#i1').attr('type')			获取匹配行type的值===button
$('#i1').attr('name','lishang')	修改匹配行name的值为'lishang',无则新增
$('#i1').removeAttr('name')		删除匹配行name属性


专门用于checkbox,radio
$('#i2').prop('checked',false);	为复选框取消选中
$('#i2').prop('checked',true);	为复选框打上对勾
##### 6、内容操作
```javascript
文本操作:
	$('#i1').text()				获取文本内容
	$('#i1').text('dada')		给这个标签的内容赋新值
	$('#i2').html()				获取全部的内容
	$('#i2').html('hello')		设置内容,解析标签
	$('#i3').val()				获取文本框里的内容
	$('#i3').val("1.1.1.1")		设置文本框里的内容
6、文档处理
$('#u1').append(tmp)		在匹配id='u1'的标签内部末尾添加tmp
$('#u1').prepend(tmp)		在匹配id='u1'的标签内部上面添加tmp
$('#u1').after(tmp)			在匹配的标签外部向下添加tmp
$('#u1').before(tmp)		在匹配的标签外部向上添加tmp
$('#u1 li').empty()			只删除标签的内容,标签本身还存在
$('#u1 li').remove()		连标签同时删掉
$('#u1 li').clone()			给匹配的标签克隆一份一样的
7、事件
1、事件的绑定方式,4,3种都是调用的最后一种on的方式
$('.c1').click()
$('.c1').....

$('.c1').bind('click',function(){})
$('.c1').unbind('click',function(){})

$('.c1').delegate('a','click',function(){})
$('.c1').undelegate('a','click',function(){})
具有委托功能,给后来添加的标签也具有和之前标签一样的绑定事件的功能,应用于例子3

$('.c1').on('click',function(){})
$('.c1').off('click',function(){})

2、阻止事件的发生
return false

3、当页面框架加载完成后自动执行,绑定事件用这种更好
$(function(){})
8、扩展

两种方式,不同的扩展方式,不同的调用方式

1、第一种:$.extend()调用
$.extend({
	'lishang': function(){
     	return 'good';
        }
});
var v = $.lishang();
alert(v)

2、第二种:
$.fn.extend({
	'lishang': function(){
     	return 'good';
        }
});
var v = $('#i1').lishang();
alert(v)

二、例子

1、多选与反选取消
<!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="clearAll();">

<table border="1" id="t1">
    <thead>
    <tr>
        <th>选项</th>
        <th>IP</th>
        <th>port</th>
    </tr>
    </thead>
    <tbody>
    <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.2</td>
        <td>443</td>
    </tr>
    <tr>
        <td><input type="checkbox"></td>
        <td>1.1.1.3</td>
        <td>3306</td>
    </tr>
    </tbody>

</table>

    <script src="jquery-1.12.4.js"></script>
    <script>
        function checkAll() {
            $('#t1: checkbox').prop('checked',true);
        }
        function clearAll() {
            $('#t1: checkbox').prop('checked',false);
        }
        function reverseAll() {
        	// $(':checkbox').each() 会自动循环所有的带有checkbox的标签
            $('#t1 :checkbox').each(function() {
                // this 代指当前循环的每个元素
                
                // 用dom实现(下面4行)
                // if(this.checked){
                //     this.checked = false;
                // }else {
                //     this.checked = true;
                // }
                
                // 用jquery实现
                // if($(this).prop('checked')){
                //     $(this).prop('checked',false);
                // }else{
                //     $(this).prop('checked',true);
                // }
                
                // 也是用jquery实现,引入了三元运算的写法,(var v = 条件?真值:假值)
                var v = $(this).prop('checked')?false:true;
                $(this).prop('checked',v);
            })
        }
    </script>
</body>
</html>
注:其中获取当前标签是否选中时用了两种方式实现,dom 和 jquery分别实现
$(':checkbox').each(function(k)
	k		指当前循环的索引
	$(this)	当前循环的元素,加上$()以后就成了jquery对象
三元运算的写法,(var v = 条件?真值:假值) 	
2、选中左侧标题展开该目录,点击另一个,打开这一个同时关闭其他
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .header{
            background-color: black;
            color: #ff755f;
        }
        .content{
            min-height: 50px;
        }
        .hide{
            display: none;
        }
    </style>
</head>
<body>
    <div style="height: 400px;width: 200px; border: 1px solid #1E84E7;">
        <div class="item">
            <div class="header">标题一</div>
            <div class="content hide">内容1</div>
        </div>
        <div class="item">
            <div class="header">标题二</div>
            <div class="content hide">内容1</div>
            <div class="content hide">内容2</div>
        </div>
        <div class="item">
            <div class="header">标题三</div>
            <div class="content hide">内容1</div>
            <div class="content hide">内容2</div>
            <div class="content hide">内容3</div>
        </div>
        <div class="item">
            <div class="header">标题四</div>
            <div class="content hide">内容1</div>
            <div class="content hide">内容2</div>
            <div class="content hide">内容3</div>
            <div class="content hide">内容4</div>
        </div>
    </div>
    <script src="jquery-1.12.4.js"></script>
    <script>
        $('.header').click(function(){

            // $(this)当前选择的标签, .siblings()所有的兄弟标签, removeClass('hide')移除class样式'hide'
            // $(this).siblings().removeClass('hide');
            // $(this).parent().siblings().find('.content').addClass('hide');

            // jquery支持链式编程
            $(this).siblings().removeClass('hide').parent().siblings().find('.content').addClass('hide');
        })
    </script>
</body>
</html>
注: jquery选择器和筛选器的使用
	jquery支持链式编程,可以一直.下去,可绕地球一圈.
3、模态对话框,暂时实现编辑,添加框,待再开发
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .c1 {
            text-align: center;
        }
        .hide {
            display: none;
        }
        .modal {
            position: fixed;
            top: 50%;
            left: 50%;
            width: 500px;
            height: 400px;
            margin-left: -250px;
            margin-top: -250px;
            background-color: #B9B9B9;
            z-index: 10;
        }
        .shadow {
            position: fixed;
            top: 0;
            right: 0;
            left: 0;
            bottom: 0;
            opacity: 0.6;
            background-color: black;
            z-index: 9;
        }
        .edit {
        }
    </style>
</head>
<body>
<a onclick="addElement();">添加</a>
<table border="1">
    <tr>
        <td class="c1">IP</td>
        <td>port</td>
        <td class="c1">操作</td>
    </tr>
    <tr>
        <td target="hostname">1.1.1.1</td>
        <td target="port">80</td>
        <td>
            <a class="edit">编辑</a> | <a>删除</a>
        </td>
    </tr>
    <tr>
        <td target="hostname">1.1.1.2</td>
        <td target="port">443</td>
        <td>
            <a class="edit">编辑</a> | <a>删除</a>
        </td>
    </tr>
    <tr>
        <td target="hostname">1.1.1.3</td>
        <td target="port">3306</td>
        <td>
            <a class="edit">编辑</a> | <a>删除</a>
        </td>
    </tr>
</table>
<div class="modal hide">
    <div>
        <input name="hostname" type="text"/>
        <input name="port" type="text"/>
    </div>
    <div>
        <input style="position: absolute;bottom: 20px;right: 20px;" type="button" value="取消" onclick="cancleModal();">
        <input style="position: absolute;bottom: 20px;left: 100px;" type="button" value="提交" onclick="commitFrom();">
    </div>
</div>
<div class="shadow hide"></div>
<script src="jquery-1.12.4.js"></script>
<script>

    function addElement() {
        $('.modal,.shadow').removeClass('hide');
    }
    function cancleModal() {
        $('.modal,.shadow').addClass('hide');
        $('.modal input[type="text"]').val("");
    }
    $('.edit').click(function () {
        $('.modal,.shadow').removeClass('hide');

        var tds = $(this).parent().prevAll();

        tds.each(function () {
            var n = $(this).attr('target');
            var text = $(this).text();
            $('.modal input[name="' +n+ '"]').val(text);
        });
        
		// 下面这四行用上面四行代替,利用each()循环更好
        // var port = $(tds[0]).text();
        // var ip = $(tds[1]).text();
        // $('.modal input[name="IP"]').val(ip);
        // $('.modal input[name="port"]').val(port);
		// });
    });
</script>
</body>
</html>
4、模态对话框,暂时实现编辑、添加、删除
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .c1 {
            text-align: center;
        }

        .hide {
            display: none;
        }

        .modal {
            position: fixed;
            top: 50%;
            left: 50%;
            width: 500px;
            height: 400px;
            margin-left: -250px;
            margin-top: -250px;
            background-color: #B9B9B9;
            z-index: 10;
        }

        .shadow {
            position: fixed;
            top: 0;
            right: 0;
            left: 0;
            bottom: 0;
            opacity: 0.6;
            background-color: black;
            z-index: 9;
        }

        .edit {

        }
    </style>
</head>
<body>
<a onclick="addElement();">添加</a>

<table border="1" id="tb">

    <tr>
        <td class="c1">IP</td>
        <td>port</td>
        <td class="c1">操作</td>
    </tr>
    <tr>
        <td target="hostname">1.1.1.1</td>
        <td target="port">80</td>
        <td>
            <a class="edit">编辑</a> | <a class="del">删除</a>
        </td>
    </tr>
    <tr>
        <td target="hostname">1.1.1.2</td>
        <td target="port">443</td>
        <td>
            <a class="edit">编辑</a> | <a class="del">删除</a>
        </td>
    </tr>
    <tr>
        <td target="hostname">1.1.1.3</td>
        <td target="port">3306</td>
        <td>
            <a class="edit">编辑</a> | <a class="del">删除</a>
        </td>
    </tr>
</table>
<div class="modal hide">
    <div>
        <input name="hostname" type="text"/>
        <input name="port" type="text"/>
    </div>
    <div>
        <input style="position: absolute;bottom: 20px;right: 20px;" type="button" value="取消" onclick="cancleModal();">
        <input style="position: absolute;bottom: 20px;left: 100px;" type="button" value="提交" onclick="commitModal();">
    </div>
</div>
<div class="shadow hide"></div>

<script src="jquery-1.12.4.js"></script>
<script>
    function addElement() {
        // 添加按钮
        // $('.modal').removeClass('hide').next().removeClass('hide');
        $('.modal,.shadow').removeClass('hide');
    };
    function cancleModal() {
        // 编辑里面的取消按钮
        $('.modal,.shadow').addClass('hide');
        $('.modal input[type="text"]').val("");
    };
    $('.edit').click(function () {
        // 编辑按钮
        $('.modal,.shadow').removeClass('hide');

        var tds = $(this).parent().prevAll();

        tds.each(function () {
            var n = $(this).attr('target');
            var text = $(this).text();
            $('.modal input[name="' +n+ '"]').val(text);
        });
    });
    $('.del').click(function () {
        // 删除操作
        $(this).parent().parent().remove();
    });
    function commitModal() {
        // 提交按钮
        var tr = document.createElement('tr');
        var td1 = document.createElement('td');
        td1.innerHTML = "1.1.1.5";
        var td2 = document.createElement('td');
        td2.innerHTML = "8080";

        $(tr).append(td1);
        $(tr).append(td2);
        $('#tb').append(tr);

        $('.modal,.shadow').addClass('hide');
    }
</script>
</body>
</html>
5.1、购物网站商品详情、规格参数、累计评价、服务详情展示
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .menu{
            height: 38px;
            background-color: #1E84E7;
            line-height: 38px;
        }
        .menu-item{
            float: left;
            border-right: 1px solid #ff755f;
            padding: 0 5px;
            cursor: pointer;
        }
        .hide{
            display: none;
        }
        .content{
            min-height: 50px;
            border: 1px solid #DBDBDB;
        }
        .active{
            background-color: #ff755f;
        }
    </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="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>
5.2、同上面的小例子实现一样,下面通过索引实现,上面通过自定义属性实现
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .menu{
            height: 38px;
            background-color: #1E84E7;
            line-height: 38px;
        }
        .menu-item{
            float: left;
            border-right: 1px solid #ff755f;
            padding: 0 5px;
            cursor: pointer;
        }
        .hide{
            display: none;
        }
        .content{
            min-height: 50px;
            border: 1px solid #DBDBDB;
        }
        .active{
            background-color: #ff755f;
        }
    </style>
</head>
<body>
<div style="width: 700px; margin: 0 auto">
    <div class="menu">
        <div class="menu-item active">菜单一</div>
        <div class="menu-item">菜单二</div>
        <div class="menu-item">菜单三</div>
    </div>
    <div class="content">
        <div>内容一</div>
        <div class="hide">内容二</div>
        <div class="hide">内容三</div>
    </div>
</div>

<script src="jquery-1.12.4.js"></script>
<script>
    $('.menu-item').click(function () {
        $(this).addClass('active').siblings().removeClass('active');
        $('.content').children().eq($(this).index()).removeClass('hide').siblings().addClass('hide');
    })
</script>
</body>
</html>
6、点赞之后出现一个+1,向右向上移动,同时透明度越来越小直至消失
<!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: 40px;
        }
    </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>

    <div style="color: #ffc070;"></div>
    <script src="jquery-1.12.4.js"></script>
    <script>
        $('.item').click(function () {
            addHavor(this);
        });
        function addHavor(self) {
            var fontSize = 15;
            var top = 0;
            var right = 0;
            var opacity = 1;

            var tag = document.createElement('span');
            $(tag).text('+1');
            $(tag).css('color','#ffc070');
            $(tag).css('position','absolute');
            $(tag).css('fontSize',fontSize + 'px');
            $(tag).css('top',top + 'px');
            $(tag).css('right',right + 'px');
            $(tag).css('opacity',opacity);
            $(self).append(tag);

            var obj = setInterval(function () {
                fontSize = fontSize + 5;
                top = top - 5;
                right = right - 5;
                opacity = opacity - 0.1;

                $(tag).css('fontSize',fontSize + 'px');
                $(tag).css('top',top + 'px');
                $(tag).css('right',right + 'px');
                $(tag).css('opacity',opacity);

                if(opacity < 0){
                    clearInterval(obj);
                    $(tag).remove();
                }
            },100);
        }
    </script>
</body>
</html>
利用setInterval(function{...},100),计时器,每个100毫秒改变一次属性达到效果
7、回到顶部
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <input id="i1" style="position: fixed;right:40px; bottom:40px; opacity: 0.5" type="button" value="回到顶部">
    <div id="i2" style="height: 500px; width: 500px ;border: 1px solid #ff755f; overflow: auto">
        <p>asdf</p><p>asdf</p><p>asdf</p><p>asdf</p>
        <p>asdf</p><p>asdf</p><p>asdf</p><p>asdf</p>
        <p>asdf</p><p>asdf</p><p>asdf</p><p>asdf</p>
        <p>asdf</p><p>asdf</p><p>asdf</p><p>asdf</p>
        <p>asdf</p><p>asdf</p><p>asdf</p><p>asdf</p>
        <p>asdf</p><p>asdf</p><p>asdf</p><p>asdf</p>
        <p>asdf</p><p>asdf</p><p>asdf</p><p>asdf</p>
    </div>
    <div style="height: 1000px;"></div>

    <script src="jquery-1.12.4.js"></script>
    <script>
        $('#i1').click(function () {
            $(window).scrollTop(0);
        })
    </script>
</body>
</html>
8.1、绑定事件,用于表单验证
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
	// Dom的方式
    <a onclick="return clickOn()" href="https://www.zhihu.com">出来</a>
    <br>
    // jQuery的方式
    <a id="i1" href="https://www.zhihu.com">出来jQuery</a>
    <script>
        function clickOn() {
            alert('123');
            return false;
        }
    </script>
    <script src="jquery-1.12.4.js"></script>
    <script>
        $('#i1').click(function () {
            alert(456);
            return false;
        });
    </script>        
</body>
</html>
注:
a标签默认有click绑定事件,如果自己再手动绑定一个事件,会先执行自定义的事件,
再执行默认事件,加上return false以后,就不会再执行默认事件了
8.2、提交信息时,没填写信息,不提交并给出提示
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .error{
            color: #ff755f;
        }
    </style>
</head>
<body>
    <form id="f1" action="s4.html" method="POST">
    <div><input name="n1" type="text" /></div>
    <div><input name="n2" type="password" /></div>
    <div><input name="n3" type="text" /></div>
    <div><input name="n4" type="text" /></div>
    <div><input name="n5" type="text" /></div>

    <input type="submit" value="提交" />
    </form>

    <script src="jquery-1.12.4.js"></script>
    <script>
        $(':submit').click(function () {

            $('.error').remove();
            var flag = true;

            $('#f1').find('input[type="text"],input[type="password"]').each(function () {
                var v = $(this).val();
                if(v.length <= 0){
                    flag = false;
                    var tag = document.createElement('span');
                    tag.className = "error";
                    tag.innerHTML = '必填';
                    $(this).after(tag);
                }
            });return flag;
        })
    </script>
</body>
</html>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值