jQuery笔记

jquery ——> dom :$('#i1')[0]
dom ——> jquery :$(this)

eg:变成dom对象后可以看到标签具体内容
<input type="button" value="开关" id="i1">
$('i1')输出 : jQuery.fn.init [input#i1]
$('#i1')[0]输出 : <input type="button" value="开关" id="i1">

 

1,选择器,筛选器
1.1,选择器
jquery里没有name选择器,可以用属性选择器
id: $("#i1")
class: $(".c1")
标签: $("a")

属性: $('[name]')具有name属性标签
$('[name="guxh"]') # 具有name="guxh"的标签
$('input[value="删除"]') # value="删除"的input标签
$('.modal input[type="text"]').val('') # class='modal'标签下,type="text"的input标签
组合: $("#i1, .c1") # id=i1和class=c1的标签
层级: $("#i1 a") # id=i1下的a标签

1.2,筛选器
:first # 第一个
:last # 最后一个
:eq(index) # 索引为index的,从0开始。eg, $('li:eq(1)') 等效于 $('li').eq(1) 找到li标签中索引为1的标签
$(this).next() # 当前标签的下一个标签
$(this).prev() # 当前标签的上一个标签
$(this).parent() # 父标签
$(this).children() # 孩子标签
$(this).siblings() # 兄弟标签
$(this).find('.content') # 找当前标签下所有的子子孙孙标签中,含有class='content'的标签
$("label + input") # 找到label标签的下一个input标签

1.3,表单选择器
可以不会,通过属性选择器去找
例如:$("input[type='text']") # 找到input,type='text'标签
如果用表单选择器,可以简写为$(:text)

表单对象属性
:enabled # $(":enabled"),应该也能用$("[enabled]")替换
:disabled
:checked
:selected


3,jquery内置循环
jquery内置循环,dom需要自己循环
例如:
$("#tb input[type='checkbox']").prop("checked", true); # 自动循环,设置true
$("#tb input[type='checkbox']").each(function(k){}) # 自动循环运行function函数
$('.i1').addClass('hide') # 自动循环,class='i1'的所有标签,添加class'hide'
$('.header').click(function{}) # 绑定事件并触发函数,自动循环所有绑定的标签


2,内容操作
$('#i1').text() # 获取文本,相当于DOM的$('#i1')[0].innerText
$('#i1').text('xyz') # 设置文本内容,如果加了html标签,只会当做字符串不会去解析
$('#i1').html() # 获取html,相当于DOM的$('#i1')[0].innerHtml
$('#i1').html('<a>asdfs</a>') # 设置html内容
$('#i1').val() # 获取value值,例如input/select/textarea标签的value
$('#i1').val('asd') # 设置value值


4,样式操作
addClass() # 增加CSS
removeClass() # 移除CSS
hasClass('.hide') # 判断是否有class"hide"
toggleClass('.hide') # 如果有class"hide",就去掉,如果没有class"hide"就加上,相当于把if...else...合成一句

5,属性操作
5.1,自定义属性操作
$('#i1').attr('name') # 获取值,获取id='i1'标签的name属性值
$('#i1').attr('name', 'guxh') # 设置值,将id='i1'标签的name属性值设置为'guxh'
$('#i1').removeAttr('name') # 删除值

5.2,check,radio操作
check,radio如果用attr去操作可能存在选不中的问题,建议用prop
$('#i2').prop('checked') # 获取值
$('#i2').prop('checked', true) # 设置值,true改成'checked'


6,索引
$('#i1').index() # 获取索引,返回当前标签在父类标签下的索引,从0开始
$('#i1').children().eq(1) # 根据索引取对象标签,索引=1的
$('#i1').children('eq(1)') # 同上,索引如果是变量,需要字符串拼接,没有上面的方便
$('#i1').children()[1] # 根据索引取对象标签,但拿到的是DOM对象,变为jquery对象需要再套个$()


7,文档处理
append() # 把某个值追加到该标签内,放最后面
prepend() # 把某个值追加到该标签内,放最后面
after() # 添加到该标签后面
before() # 添加到该标签前面
empty() # 清空内容,标签还在
remove() # 删除内容,标签消失
clone() # 克隆内容

8,CSS处理
object.css('样式名称', '样式值')

9,位置
$('#i1').scrollTop() # 获取滚轮位置(距离顶部)
$(window).scrollTop() # 获取整个窗口的滚轮位置
$('#i1').scrollTop(0) # 设置div的滚轮位置,为0相当于返回顶部
$(window).scrollTop(0) # 设置整个窗口的滚轮位置,为0相当于返回顶部
$('#i1').scrollRight([val]) # 距离右边
$('#i1').scrollLeft([val]) # 距离左边

$('#i1').offset() # 指定标签在html标签中的坐标,可以继续.left,.top取单个位置
$('#i1').position() # 获取指定标签在父标签(relative)中的位置

$('#i1').height() # 获取标签的高度
$('#i1').innerHeight()
$('#i1').outerHeight()
$('#i1').outerHeight(true)

10,jquery事件绑定方式:
10.1,绑定方式
绑定方式一:
$('.c1').click
绑定方式二:
$('.c1').bind('click', function(){
})
$('.c1').unbind('click', function(){ //解绑定
})
绑定方式三:
$('.c1').delegate('a', 'click', function({ // c1下面所有的a标签,绑定个function
}))
$('.c1').delegate('a', 'click', function({ // 解绑定
}))
绑定方式四:
$('.c1').on('click', function(){
})
$('.c1').off('click', function(){
})
备注:
前三种绑定方式,内部都是调用第四种绑定方式;
用第三种绑定方式有委托功能,即有新增标签时也能够绑定执行,另外几种不具备委托功能

10.2,阻止默认事件发生
a标签默认有一个onclick事件,即跳转。
如果新绑定了一个事件,则默认onclick跳转事件会放后面执行。
如果想阻止默认onclick跳转事件执行,方法如下:
DOM方式:绑定时onclick = "return clickOn()",然后clickOn()中return false
jquery方式:$("#i1").click中return false

11,页面加载完成后自动执行
11.1,当页面框架加载完成后自动执行
$(function(){
})

11.2,当页面所有元素加载完成后自动执行
$('#i1').click(){
}

区别是方法一种,如果有img图片,无需等待img图片完全加载后才执行函数

12,jquery的扩展
12.1,jquery默认的方法
$('#i1').css() // jquery选择器调用
$.ajax() // jquery函数直接调用

12.2,jquery扩展方式一
$.extend({
'guxh': function(){
}
})
$.guxh() // 调用

12.3,jquery扩展方式二
$.fn.extend({
'guxh': function(){
}
})
$('#I1').guxh() // 调用

12.4,引入第三方扩展插件之间全局变量名重复的问题
使用自执行函数,由于变量的作用域是函数,因此不同插件可以重复
(function(arg){
var status = 1
arg.extend({
'guxh' : function(){
……
}
})
})(jQuery) // jQuery写成$也行

 

 

6,其他
可以用这个做测试:id="i1"标签下所有input标签,点击时会触发提示当前选中的标签
$('#i1 input').click(function () {
console.log(this)
})

 

样例一,实现全选,反选,取消

<body>
    <input type="button" value="全选" onclick="checkAll()">
    <input type="button" value="反选" onclick="reverseAll()">
    <input type="button" value="取消" onclick="cancelAll()">
    <table border="1" id="tb">
        <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>2.2.2.2</td>
                <td>80</td>
            </tr>
            <tr>
                <td><input type="checkbox"></td>
                <td>3.3.3.3</td>
                <td>80</td>
            </tr>
            <tr>
                <td><input type="checkbox"></td>
                <td>4.4.4.4</td>
                <td>80</td>
            </tr>
            <tr>
                <td><input type="checkbox"></td>
                <td>5.5.5.5</td>
                <td>80</td>
            </tr>
        </tbody>
    </table>

    <script src="jquery-3.3.1.js"></script>
    <script>
        function checkAll() {
            $("#tb input[type='checkbox']").prop("checked", true);  // prob可以自动循环
        }
        function cancelAll() {
            $("#tb input[type='checkbox']").prop("checked", false);
        }
        function reverseAll() {
            $("#tb input[type='checkbox']").each(function (k) {   // .each也可以自动循环选中的每一个元素
                if(this.checked){     // k是索引下标(这里没用到),this代指当前循环的每一个元素,this是dom对象,$(this)是JQuery对象
                    this.checked = false
                }else{
                    this.checked = true
                }
            })
        }
    </script>
</body>

 

备注1:reverseALL()也可以用jquery实现,方法如下:

	function reverseAll() {
		$("#tb input[type='checkbox']").each(function (k) {  
			if($(this).prop('checked')){
				$(this).prop('checked', false)
			}else{
				$(this).prop('checked', true)
			}
		})
     }

  

备注2:reverseALL()也可以用jquery + 三元运算实现,方法如下:

    function reverseAll() {
        $("#tb input[type='checkbox']").each(function (k) {   
            var v = $(this).prop('checked')?0:1;   // 用false:true报错了,不知道为什么
            $(this).prop('checked', v);
        })
   

 




样例二,菜单栏中实现点击标题后,隐藏/取消隐藏

<body>
    <div style="height: 400px; width: 200px; border: 1px solid #dddddd">
        <div class="item">
            <div>
                <div class="header">标题一</div>
                <div class="content">内容</div>
            </div>
            <div>
                <div class="header">标题二</div>
                <div class="content hide">内容</div>
            </div>
            <div>
                <div class="header">标题三</div>
                <div class="content hide">内容</div>
            </div>
        </div>
    </div>

    <script src="jquery-3.3.1.js"></script>
    <script>
        $('.header').click(function () {   // 所有.class标签绑定onclick标签
            console.log(this);
            $(this).next().removeClass('hide');     // 当前点击标签的下一个标签,移除hide CSS
            $(this).parent().siblings().find('.content').addClass('hide');   // 获取当前点击标签的父标签的兄弟标签,下面每个content加上hide CSS
        })
    </script>
</body>

 

备注:jquery链式编程,可以一行解决
$(this).next().removeClass('hide').parent().siblings().find('.content').addClass('hide');

 


样例三,模态对话框

<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .hide{
            display: none;
        }
        .modal{
            position: fixed;
            top: 50%;
            left: 50%;
            width: 500px;
            height: 400px;
            margin-top: -250px;
            margin-left: -250px;
            z-index: 10;
            background-color: #eeeeee;
        }
        .shadow{
            position:fixed;
            top:0;
            left:0;
            right:0;
            bottom:0;
            opacity: 0.6;
            z-index: 9;
            background-color: black;
        }
    </style>
</head>

<body>
    <div class="modal hide" >    <!--弹出层-->
        <input name="hostname" type="text" style="display: block"/>
        <input name="port" type="text" style="display: block"/>
        <input type="button" value="确定">
        <input type="button" value="取消" onclick="cancelModal()">
    </div>

    <div class="shadow hide"> </div>    <!--中间遮罩层-->

    <table border="1" id="tb">
        <input type="button" value="添加" onclick="addElement()">
        <thead>
            <tr>
                <th>选项</th>
                <th>IP</th>
                <th>PORT</th>
                <th>操作</th>
            </tr>
        </thead>
        <tbody id="i1">
            <tr>
                <td><input type="checkbox"></td>
                <td>1.1.1.1</td>
                <td>80</td>
                <td><input class='edit' type="button" value="编辑"><input type="button" value="删除"></td>
            </tr>
            <tr>
                <td><input type="checkbox"></td>
                <td>2.2.2.2</td>
                <td>80</td>
                <td><input class='edit' type="button" value="编辑"><input type="button" value="删除"></td>
            </tr>
            <tr>
                <td><input type="checkbox"></td>
                <td>3.3.3.3</td>
                <td>80</td>
                <td><input class='edit' type="button" value="编辑"><input type="button" value="删除"></td>
            </tr>
            <tr>
                <td><input type="checkbox"></td>
                <td>4.4.4.4</td>
                <td>80</td>
                <td><input class='edit' type="button" value="编辑"><input type="button" value="删除"></td>
            </tr>
            <tr>
                <td><input type="checkbox"></td>
                <td>5.5.5.5</td>
                <td>80</td>
                <td><input class='edit' type="button" value="编辑"><input type="button" value="删除"></td>
            </tr>
        </tbody>
    </table>

    <script src="jquery-3.3.1.js"></script>
    <script>
        function addElement() {
            $('.modal,.shadow').removeClass('hide');
        }

        function cancelModal() {
            $('.modal,.shadow').addClass('hide');
            $('.modal input[type="text"]').val('');  // 需要清空下,否则按添加时也会有默认值
        }

        $('.edit').click(function () {
            $('.modal,.shadow').removeClass('hide');
            var tds = $(this).parent().prevAll();   // tds是DOM
            $('[name="host"]').val($(tds[1]).text());
            $('[name="port"]').val($(tds[0]).text());
        })
    </script>
</body>

 


样例四,用自定义属性对样例三做改进,增加添加/删除功能
如果样例三中,编辑的项目比较多,需要取值赋值N次,而且要按顺序取值赋值,中间要加减列项的时候全都要调整

<body>
    <div class="modal hide" >    <!--弹出层-->
        <input name="hostname" type="text" style="display: block"/>
        <input name="port" type="text" style="display: block"/>
        <input type="button" value="确定" onclick="confirmModal()">
        <input type="button" value="取消" onclick="cancelModal()">
    </div>

    <div class="shadow hide"> </div>    <!--中间遮罩层-->

    <table border="1" id="tb">
        <input type="button" value="添加" onclick="addElement()">
        <thead>
            <tr>
                <th>选项</th>
                <th>IP</th>
                <th >PORT</th>
                <th>操作</th>
            </tr>
        </thead>
        <tbody id="i1">
            <tr>
                <td><input type="checkbox"></td>
                <td target="hostname">1.1.1.1</td>
                <td target="port">80</td>
                <td><input class='edit' type="button" value="编辑"><input type="button" value="删除"></td>
            </tr>
            <tr>
                <td><input type="checkbox"></td>
                <td target="hostname">2.2.2.2</td>
                <td target="port">80</td>
                <td><input class='edit' type="button" value="编辑"><input type="button" value="删除"></td>
            </tr>
            <tr>
                <td><input type="checkbox"></td>
                <td target="hostname">3.3.3.3</td>
                <td target="port">80</td>
                <td><input class='edit' type="button" value="编辑"><input type="button" value="删除"></td>
            </tr>
            <tr>
                <td><input type="checkbox"></td>
                <td target="hostname">4.4.4.4</td>
                <td target="port">80</td>
                <td><input class='edit' type="button" value="编辑"><input type="button" value="删除"></td>
            </tr>
            <tr>
                <td><input type="checkbox"></td>
                <td target="hostname">5.5.5.5</td>
                <td target="port">80</td>
                <td><input class='edit' type="button" value="编辑"><input type="button" value="删除"></td>
            </tr>
        </tbody>
    </table>

    <script src="jquery-3.3.1.js"></script>
    <script>
        function addElement() {
            $('.modal,.shadow').removeClass('hide');
        }

        function cancelModal() {
            $('.modal,.shadow').addClass('hide');
            $('.modal input[type="text"]').val('');  // 需要清空下,否则按添加时也会有默认值
        }

        $('.edit').click(function () {
            $('.modal,.shadow').removeClass('hide');
            var tds = $(this).parent().prevAll();  // tds是DOM
            tds.each(function () {
                var n = $(this).attr('target');  // this是DOM对象,需要转换为jquery对象
                var text = $(this).text();
                $('.modal input[name="' + n + '"]').val(text);  // 字符串拼接
            })
        })
        
        $('input[value="删除"]').click(function () {
            $(this).parent().parent().remove();
        });
        
        function confirmModal() {
            // var trs = [];
            tr = document.createElement('tr');
            tr.append("<td><input type="checkbox"></td>");     // 这里添加HTML标签失败了,变成字符串,但是样例7成功了,待解决问题  
            $('.modal input[type="text"]').each(function () {
                var td = document.createElement('td');
                text = $(this).val();
                id = $(this).attr('name');
                $(tr).append(td);
            });
            tr.append('<td><input class=\'edit\' type="button" value="编辑"><input type="button" value="删除"></td>');   // 这里添加HTML标签失败了,
            console.log(tr)
            $('#i1').append(tr)
        }
    </script>
</body>

 


样例五,TAB菜单 - 自定义属性方法实现

<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .menu{
            height: 38px;
            background-color: #dddddd;
            line-height: 38px;
        }
        .menu-item{
            float:left;
            border-right: 1px solid red;
            padding: 0 10px;    /*菜单间有一定距离*/
            cursor: pointer;    /*选中时变小手*/
        }
        .content{
            border: 1px solid #eeeeee;
            min-height: 100px;
        }
        .hide{
            display: none;
        }
        .active{
            background-color: #d9534f;
        }
    </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-3.3.1.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>

 


样例六,TAB菜单 - 索引方法实现
把HTML标签中的a='x', b='x'全部去掉

<script>
        $('.menu-item').click(function () {
            $(this).addClass('active').siblings().removeClass('active');
            var v = $(this).index();
            $('.content').children().eq(v).removeClass('hide').siblings().addClass('hide');
            // $($('.content').children()[v]).removeClass('hide').siblings().addClass('hide');    // 用[v]获取是DOM对象,所以再转成jquery对象
        })
</script>

 


样例七,添加内容到最后面,根据索引删除/清空内容,复制内容

 <input id="t1" type="text"/>
    <input id="a1" type="button" value="添加"/>
    <input id="a2" type="button" value="删除"/>
    <input id="a3" type="button" value="复制"/>
    <ul id="u1">
        <li>1</li>
        <li>2</li>
    </ul>

    <script src="jquery-3.3.1.js"></script>
    <script>
        $('#a1').click(function () {
            var v = $('#t1').val();
            var temp = "<li>" + v + "</li>";
            $('#u1').append(temp);
        });
        $('#a2').click(function () {
           var index = $('#t1') .val();
           // $('#u1 li').eq(index).empty();  // empty是清空,标签还在
           $('#u1 li').eq(index).remove();
        });
        $('#a3').click(function () {  
           var index = $('#t1') .val();
           var v = $('#u1 li').eq(index).clone();  // 拿到的是jquery对象
           $('#u1').append(v);   // jquery对象和DOM对象都可以直接添加
        });
    </script>

 


样例八,CSS点赞

<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-3.3.1.js"> </script>
<script>
    $('.item').click(function () {
        addFavor(this)
    });

    function addFavor(self) {
        var fontSize = 15;
        var top = 0;
        var right = 0;
        var opacity = 1;
        var tag = document.createElement('span');  // 新建span标签,并加上+1的text内容
        $(tag).text('+1');
        $(tag).css('color', 'green');
        $(tag).css('position', 'absolute');
        var v = $(self);   // v是DOM对象,转为jquery对象后,append新创建的tag
        $(self).append(tag);
        var obj = setInterval(function () {
            fontSize = fontSize + 5;
            top = top - 5;
            right = right - 8;
            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();   // 当前的tag标签也要移除,否则标签还在那,只是效果显示完了
            }
        }, 100);
    }
</script>
</body>

 

 

样例九,表单验证

<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .error{
            color: red;
        }
    </style>
</head>
<body>
    <form id='i1' action="s5.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>
        <div><input type="submit" value="提交"/></div>
    </form>
<script src="jquery-3.3.1.js"> </script>
<script>
    $(':submit').click(function(){    // input=submit的标签
        $('.error').remove();    // 错误内容需要清空下,error样式主要用于清空,其次可以加个style
        var flag = true;
        $('#i1').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>

 

posted @ 2018-10-05 14:57  GUXH  阅读(475)  评论(0编辑  收藏  举报