jquery

  • ​ 压缩版:生产上用,容量小,加载速度快,后面带.min.js,可读性差,官网链接如下:

  • 访问jquery 对象通用方法

    $('#div1') //引号内是要找到id名或类名
    $('#div2').text('hello') //获取到对象之后用text()方法直接设置值,这是jquery自己的方法,不用用dom的方法,原生js获取的dom对象也不能使用jquery的方法,但是两者之间可以转换
    //text()里面不加内容就是获取文本的功能
    
  • 转换

    //jquery 转 dom对象可以在后面加索引的方式
    $('#div1')[0] //如图6302
    //dom 转jquery 对象,直接在对象括号外加$
    var a = $('#div1')[0] //这里a就是dom对象,网页div元素,在外层加括号,加$就可以转换成jquery对象,比如(图6303):
    $(a)
    
    

  • jquery API中文文档链接 https://jquery.cuishifeng.cn/

  • jquery 基本语法

    //基本选择器(括号内引号内可以是标签名、类名、id、还可以逗号隔开组合、还可以标签.类名)
    $('')  //等价于jQuery('')
    $('#d1')  //引号内输入#d1表示获取id为d1的标签
    $('.c1')[0] //引号内输入.c1 表示获取类class为c1的标签,这里可能找到多个标签,会放到数组里,可以用索引[0]单个访问
    $('d1,d2') //引号内输入d1,d2表示组合,同时获取d1和d2的标签
    $('div.c2') //筛选所有类名是c2的div标签
    $('*') //筛选所有的标签
    
    //层级选择器
    $('a b')  //查a内所有子孙b标签
    $('a > b') //查a内所有儿子标签b
    $('a + b') //查a后面的紧跟着的1个兄弟b标签
    $('a ~ b') //查a后面的所有兄弟b标签
    
    //基本筛选器
    $('li:first') //获取的li列表里选择第一个,其实是先做了li的选择,然后从选择结果再筛选
    $('li:last') //最后一个
    $('li:eq(1)') //筛选索引等于1的元素标签
    $('li:gt(3)') //筛选索引大于3的元素标签
    $('li:lt(3)') //筛选索引小于3的元素标签
    $('li:even') //筛选索引是偶数的元素标签
    $('li:odd') //筛选索引是奇数的元素标签
    $('li:not(#l2)') //筛选li标签中id不是l2的li标签,not()括号里是基本选择器,比如可以是id,class,可以是标签名div,span等
    $('li:has(span)') //筛选li标签中包含有span的标签,这里has能匹配li内部的标签或标签id 标签类,不能匹配li本层的id 或者类名,最终筛选结果还是li标签
    
    //属性选择器( 用中括号[])
    $('[id=l4]') //中括号内是 “属性=值” ,比如性别radio 可以这样筛选:$('[name=sex]')
    $('[id!=l4]') // 属性不等于值的 筛选出来 ,常用于input标签的筛选,比如
    $('input[type="submit"]') //筛选出type=submit的input标签
    
    //表单选择器
    $(':text') //查找input标签中type类型为text的标签,如果有<div type="text">aaa</div>,这个div是筛选不出的,表单选择器只对input有效
    $(':password') //查找input标签中type类型为password的标签
    $(':submit') //查找input标签中type类型为submit的标签
    $(':radio') //查找input标签中type类型为radio的标签
    $(':checkbox') //查找input标签中type类型为checkbox的标签
    $(':button') //查找input标签中type类型为button的标签
    $(':file') //查找input标签中type类型为file的标签
    $(':reset') //查找input标签中type类型为reset的标签
    
    
    //表单对象属性
    $(':enabled') //选择能用的
    $(':disabled') //选择禁用的
    $(':checked') //选择勾选的
    $(':selected') //选择下拉框标签<select>选中的 ,如果要获取值,可以在后面加.text(),但是input的text文本框标签获取值是:$('input[name=username]').val()
    
    //筛选器方法
    $(':text').next()//找到表单里type为text的标签的下一个兄弟标签,next() 可以后面再加一个next(),链式
    $(':text').nextAll() //找到表单里type为text的标签的之后的所有的兄弟标签
    $(':text').prev()
    $(':text').prevAll() //从下往上找兄弟标签
    $(':text').parent() //找父标签
    $(':text').parentsUntil('body') //找父标签 直到body为止,但不包含body
    $('#d1').children() //儿子们
    $('#d1').siblings() //兄弟们
    
  • 进阶查询

    $('ul').find('li') //查ul下面的所有的li标签
    $('input').filter('#pwd') //在input标签里过滤出id是pwd的标签
    $('input').first() //筛选出input标签里的第一个
    $('input').last()
    $('input').not('#pwd') //筛选出input标签里 id不是pwd的标签
    $('select').has('#opt1') //筛选出select标签 的后代中,含有id为opt1的标签
    
    
  • 【以上都是查找某个标签】

  • 样式操作

    <style>
            .div1{
                background-color: pink;
                width:100px;
                height:100px;
            }
            .div2{
                background-color: purple;
            }
    </style>
    <div class='div1'>  
    </div>
    
    $('.div1').addClass('div2') //给class为div1的标签增加类div2 ,这里后面的div2前不用加点
    $('.div1').removeClass('div2') //移除
    $('.div1').hasClass('div2')  //判断是否含有div2类
    $('.div1').toggleClass('div2') //切换css类名,意思是原先如果没有div2 就增加上,如果原先有就删除
    $('.div1').css('backgroud-color','red') //把div1标签的背景色设置成red
    $('.div1').css({'background-color':'red','width':'200px'}) //同时设置多个属性值
    
  • 位置操作

        <style>
            .div1{
                background-color: pink;
                width:100px;
                height:100px;
                position:relative;
            }
            .div2{
                width:20px;
                height:20px;
                background-color: red;
            }
        </style>
        
        <div class="div1 ">
        <div class="div2">
        </div>
        </div>
        
    
    $('.div1').offset() //获取相对窗口左上角的偏移量
    $('.div2').offset({'left':'20','top':'20'}) //把div2标签 相对窗口向右向下移动20
    $('.div2').offset() //再查看div2的相对窗口左上角的偏移量是20,20
    $('.div2').position() //但是div2的标签的position()是找它的祖辈标签中含有position是relative的标签,然后返回相对这个标签左上角位置的偏移量
    $(window).scrollTop() // 滚轮向下移动的距离
    $(window).scrollLeft() //滚轮向右移动的距离
    
    
  • 事件绑定

    <div class="div1"></div>
    
     <script>
             $('.div1').click(function(){$(this).css('backgroundColor','red')})
     </script> 
    <!-- 没调试成功 -->
    <!-- 【20201222】因为dom文档还没有加载完,就执行了script脚本,相当于没找到.div1,所以这句代码应该放在$(document).ready(function(){ xxxxx })内, 写成如下:-->
    $(document).ready(function(){
              $('.div1').css('background-color','red')
              $('.div1').click(function(){alert('hello');})
          })
    
    <!-- 滚轮滚动之后显示返回顶部按钮 -->
        <style>
            .back{
                background-color: pink;
                width:50px;
                height:50px;
                position:fixed;
                left:50px;
                bottom:50px;
            }
            .hide{
                display: none;
            }
            .div1{
                height:2000px;
            }
        </style>
        <script src="jquery-3.5.1.js"></script>
        <script>
            //滚轮滚动事件
            $(window).scroll(function(){ 
                if($(window).scrollTop()>200){$('.back').removeClass('hide')}
                else{$('.back').addClass('hide')}
            })
            //点击返回顶部事件
            $('.back').click(function(){$(window).scrollTop(0);})
        </script>
        
        
        <div class="div1"></div>
        <div class="back hide"><a href="">返回顶部</a></div>
    
    
    
    <!--还可以用锚点回到顶部-->
    <div name="top"></div> 
    <div class="div1"></div>
    <a href="#top">返回顶部</a>
    
  • 尺寸

    	<style>
            .div1{
                width:200px;
                height:200px;
                background-color: pink;
                padding:20px;
                margin:30px;
                border:2px solid red;
            }
        </style>
        
        <div class="div1">
        	<span class="span1">hello</span>
        </div>
    
    $('.div1').width() //content内容的宽度,就是style里 .div1样式里的width=200
    $('.div1').height() //内容高度=200
    $('.div1').innerWidth() //内容宽度+两边的padding宽度=240
    $('.div1').innerHeight() //240
    $('.div1').outerWidth() //内容宽度+两边的padding+两边的border=244
    $('.div1').outerHeight() //244
    
  • 文本操作

    <div class="div1">
        <span class="span1">hello</span>
    </div>
    
    $('.div1').html() //获取div1内的所有内容包括标签
    $('.div1').text() //获取div1内的内容,不包括标签
    $('.div1').html('<a href="#">hahah</a>') //设置div1内的标签和内容
    $('.div1').text() //只设置文本,就算里面有<a></a>也没有标签效果
    

【20201221】

  • 值操作

    <div class="div1">
        用户名:<input type="text" name="username">
        <br>
        性别:<input type="radio" name="sex">男
        <input type="radio" name="sex" checked="true">女
        <br>
        爱好:
        <input type="checkbox" name="hobby" checked="true">游戏
        <input type="checkbox" name="hobby">睡觉
        <input type="checkbox" name="hobby">吃饭
    
        <br>
        城市:<select name="" id="city">
            <option value="1">北京</option>
            <option value="2" selected="true">上海</option>
            <option value="3">武汉</option>
            <option value="4">天津</option>
        </select>
    </div>
    
    $('[name=username]').val() //获取文本框username的值,用属性筛选的方式,很多种,还可以根据id,class
    $(':text').val() //表单筛选器获取文本框内容
    $(':text').val('Tom') //设置值
    
    $('[name=hobby]').val(['game','sleep','eat']) //设置所有的爱好多选框的值value
    $('[name=hobby]').val() //获取第一个hobby的value,这里是value,结果是“game” 而不是“游戏”
    
    var a = $(':checkbox:checked');
    for (var i=0;i<a.length;i++){console.log(a.eq(i).val());} //循环获取选中的多选框的value方法
    //先获取jQuery对象,然后循环遍历jQuery对象,用eq的方式,括号内i是索引
    
    $('#city').val() //下拉框,根据select标签的id  city 来获取value,选中哪个显示的就是哪个option的value
    
  • 属性操作

    <input type="radio" name="sex">男
    
    $(':radio').attr('name') //sex ,获取radio按钮的name属性值
    $(':radio').attr('value','1') //设置radiobutton value属性值为1
    $(':radio').attr('my','hahah')  //设置自定义属性my 为hahah
    $(':radio').removeAttr('my')  //移除属性my
    $(':radio').attr({'attr1':'hello','attr2':'world'}) //设置多个属性-值对
    
    //prop 和 attr都是属性
    //当单选框没有点击时
    $(':radio').attr('checked')  //undefined
    $(':radio').prop('checked')  //false
    
    //当单选框点击后
    $(':radio').attr('checked')  //undefined
    $(':radio').prop('checked')  //true
    
    //当没有点击时,设置checked的值,以下四种方式都能选中,亲测
    $(':radio').prop('checked','checked')
    $(':radio').attr('checked','checked')
    $(':radio').attr('checked','true')
    $(':radio').prop('checked','true')
    
    <input type="checkbox" name="sex" value="1">吃饭
    <input type="checkbox" name="sex" value="2">睡觉
    <input type="checkbox" name="sex" value="3">打游戏
    
    $(':checkbox').val(['1','3']) //可以同时选中1和3
    
  • 测试

    <div>
      <input type="button" id="choose-all" value="全选">
      <input type="button" id="reverse" value="反选">
      <input type="button" id="choose-none" value="取消">
      <table border="1">
          <thead>
              <tr>
                  <th>#</th>
                  <th>姓名</th>
                  <th>爱好</th>
              </tr>
          </thead>
          <tbody>
              <tr>
                  <th><input type="checkbox"></th>
                  <th>tom</th>
                  <th>吃饭</th>
              </tr>
              <tr>
                  <th><input type="checkbox"></th>
                  <th>jerry</th>
                  <th>吃饭</th>
              </tr>
          </tbody>
      </table>
    </div>
    
    $('#choose-all').click(function(){
          $(':checkbox').prop({'checked':true});
      })
      $('#choose-none').click(function(){
          $(':checkbox').prop({'checked':false});
      })
      $('#reverse').click(function(){
          var checkbox_list = $(':checkbox');
          for (var c=0;c<checkbox_list.length;c++){checkbox_list.eq(c).prop('checked',!(checkbox_list.eq(c).prop('checked')))}
      })
    

【20201222】

  • 文档处理

    $(document).ready(function(){
                var a = document.createElement('a');
                a.href='https://www.baidu.com';
                a.text='百度';
                $('.div1').append(a) //在.div1标签内增加一个a标签,或者用下面的appendTo 方向是是反的
        		$(a).appendTo('.div1')  //还可以$(a).appendTo($('.div1'))
            })
    
    
    //另外
    $('.div1').append('<a href="https://www.baidu.com">百度</a>') //还可以直接添加字符串,很方便
    $('.div1').prepend(a) //在.div1的前面增加标签
    $('.div1').after(a) //把a标签放在.div1后面 等价于下面的
    $(a).insertAfter('.div1')
    $('.div1').before(a) //把a放在.div1前面,下同
    $(a).insertBefore('.div1')
    
    $('.div1').remove() //删除匹配到的所有内容包括标签和子标签
    $('.div1').empty() //清空匹配到的标签内的内容,保留匹配到的标签本身
    
    var a = document.createElement('a');
    a.href='https://www.baidu.com';
    a.text='百度';
    $('span').replaceWith(a); //可以把匹配到的所有span标签替换成a标签,a的文本是百度 等价于:
    $(a).replaceAll('span'); //和上面功能一致
    
    
    			
    
    
    <!-- clone() 克隆 -->
    <div class="div1">
        <span>我是span标签</span>
        <a href="">我是a标签</a>
    </div>
    <input type="button" value="提交">
    
    <script>
            $(document).ready(function(){
                $('input:button').click(function(){
                    var clone1 = $('.div1').children().clone(true); //克隆一份,这里连事件一起克隆,比如按钮克隆一份,新的按钮也响应同样的事件,如果写成clone(),里面没有true
                    $('.div1').append(clone1); //追加到div1内后面
                })
            })
        </script>
    
  • js实现模态对话框,在表格中新增一行内容

    <!-- head -->     
    <style>
           table,tr,td{border:1px solid purple;}
           body{z-index: 0;}
    
          .modal{
              width:300px;
              height:200px;
              position:fixed;
              top:50%;
              left:50%;
              margin-left:-150px;
              margin-top:-100px;
              z-index: 100;
              border-radius: 10px;
              background-color: white;
          }
    
          .hide{ display:none;}
    
          .cover{
              background-color:rgba(0,0,0,0.3);
              position:fixed;
              top:0;
              left:0;
              right:0;
              bottom:0;
    
              z-index:99;
          }
        </style>
    
       <!-- body -->
        <div class="div1">
        <input type="button" value="增加" name="add">
        <input type="text" name="test">
        <table>
            <tr class="tr_head">
                <td>姓名</td>
                <td>年龄</td>
                <td>爱好</td>
            </tr>
            <tr>
                <td>Tom</td>
                <td>22</td>
                <td>吃饭,睡觉</td>
            </tr>
            <tr>
                <td>Jerry</td>
                <td>21</td>
                <td>打游戏</td>
            </tr>
        </table>
        </div>
        <div class="cover hide"></div>
        <div class="modal hide">
            添加内容:<br>
            姓名:<input type="text" name="user_name"> <br>
            年龄:<input type="text" name="age"> <br>
            爱好:<input type="text" name="hobby"> <br>
            <input type="submit"><input type="button" name="cancel" value="取消">
        </div>
    
    	<script>
            $('input[name=add]').click(function(){//增加按钮事件
                  $('.modal,.cover').removeClass('hide'); //把hide类去掉
                  $('input[name=user_name]').val(''); //把下面三个文本框清空
                  $('input[name=age]').val('');
                  $('input[name=hobby]').val('');
    
              })
    
              $('input:submit').click(function(){
                  var td1 = document.createElement('td'); //动态创建一堆表格里的东西
                  $(td1).text($('input[name=user_name]').val());
                  var td2 = document.createElement('td');
                  $(td2).text($('input[name=age]').val());
                  var td3 = document.createElement('td');
                  $(td3).text($('input[name=hobby]').val());
                  var tr = document.createElement('tr');
                  $(tr).append(td1); //组装
                  $(tr).append(td2);
                  $(tr).append(td3);
                  $('.tr_head').after(tr);
                  $('.modal,.cover').addClass('hide');
              })
    
              $('input[name=cancel]').click(function(){
                  $('.modal,.cover').addClass('hide');
              })
        </script>
    
  • 事件

    $(':button').click(function(){alert('hello');}) //绑定事件2中方式
    $(':button').on('click',function(){alert('hello');})
    
    .focus() //获得光标事件
    .blur() //失去光标
    .change() //文本改变
    .hover() //鼠标悬停
    
    .mouseenter() //鼠标在标签上时
    .mouseout() //鼠标离开标签时
    .mouseover() //mouseover 是当标签内也嵌套着标签的话,内部标签也触发绑定的事件,上面2个方式,内部标签就不触发
    
    $('.div1').hover(function(){$(this).css('background-color','red');},function(){$(this).css('background-color','pink')});  //相当于下面2句代码
    $('.div1').mouseenter(function(){$(this).css('background-color','red')})
    $('.div1').mouseout(function(){$(this).css('background-color','pink')})
    
     
    $(window).keydown(function(){$('.div1').css('background-color','red')}) //键盘按下
    $(window).keyup(function(){$('.div1').css('background-color','pink')}) //键盘释放
    
    //input事件
    <input type="text">
    $('input').on('input',function(){console.log($(this).val());}) //input文本框每次输入都会在控制台重新输出一遍整个文本框的内容
    
  • 阻止事件冒泡

    <div>
        <p>
            <span>点我</span>
        </p>
    </div> <!--这里有3层标签,我们分别绑定三个click事件-->
    
    $('span').click(function(e){  //点击“点我”的时候,如果不加阻止,就会顺着往父层走,碰到click事件就响应,因此应该在孩子标签这里阻止,有2种方式,return false  和  e.stopPropagation();这里的e是事件本身,事件本身也是个对象,也可以写成event
        alert('span');
    	//return false;
        e.stopPropagation();
    })
    
    $('p').click(function(e){
        alert('p');
    })
    
    $('div').click(function(e){
        alert('div');
    })
    
  • 事件委托

    <!--
    现在完成在div内动态添加一个span标签,让他响应点击事件
    -->
    <input type="button" value="add">
    <div>
        <span>点我</span>
    </div>
    <script>
    $('span').click(function(){
                    alert('span');
                })
    
                $('input[type=button]').click(function(){
                    var span1 = document.createElement('span');//创建另一个span标签
                    $(span1).text('点我。。');
                    $('div').append(span1); //我们以为新的span标签可以响应alert,但是并没有
                })
    </script>
    <!--
    增加的按钮并没有响应点击事件,需要改进
    -->
    
    
               $('span').click(function(){
                    alert('span');
                    return false; //这里增加一个阻止冒泡响应
                })
     
                $('input[type=button]').click(function(){
                    var span1 = document.createElement('span');
                    $(span1).text('点我。。');
                    $('div').append(span1);
                })
    
                $('div').on('click','span',function(){  //这里增加一个父标签div的委托事件,里面让span响应
                    alert('span');
                })
    
  • 页面加载

    //写js代码之前,有2中方式写页面加载
    $(document).ready(funstion(){})  //1
    $(function(){}) //2
    //如果有多个js包要引入,要先引入jquery.js
    

    【20201223】

  • each函数

    //迭代数组和类似字典表的存储结构
    li=[1,2,3,4,5];
    $.each(li,function(i,v){console.log(i,v)}); //i是索引,v是数组里的值,each括号内前面是数据结构,后面是一个函数function
    
    var ageList={'Jerry':25,'Tom':23}
    $.each(ageList,function(k,v){console.log(k,v)});
    
    //.each(function(index, Element)) 描述:遍历一个jQuery对象,为每个匹配元素执行一个函数。
    $('li').each(function({
    	$(this).addClass('c1'); //为匹配的每一个li标签执行一个function,即增加一个样式c1,这里的this永远对应当前遍历的li,即所谓的上下文语境中的li
    }))
    
    //蛋是 :遍历jQuery集合中的元素 - 被称为隐式迭代的过程,因此可以忽略each方法,直接写成:
    $('li').addClass('c1');
    
    //each循环控制,return 、 return false
    $('li').each(function(i){
    	console.log($(this).val());
    	if(i==1){
    		return false;//跳出循环,只输出了第一个li的value属性值,类似于break
    	}
    })
    
    $('li').each(function(i){
    	console.log($(this).val());
    	if(i==1){
    		return; //继续,只有第二个li的value值没有输出,其他的都输出,终止本次循环,类似于continue
    	}
    })
    
  • data()方法

    $('li:first').data('name','tom') //可以设置任何值
    $('li:first').data('age',25)
    $('li:first').data('hobby',['吃饭','睡觉'])
    $('li:first').data() //结果{name: "tom", age: 25, hobby: Array(2)}
    
    $('li:first').removeData('age') //移除data
    $('li:first').data() //结果 {name: "tom", hobby: Array(2)} 少了age
    
posted on 2020-12-17 19:08  94小渣渣  阅读(79)  评论(0编辑  收藏  举报