jQuery examples of common methods and exercises

Highlights:

    1, jQuery internal closed loop method:

            $ ( 'Div') css ( 'backgroundColor', 'red'):. Adding a red background to all DIV tags

    2, this appears in the jQuery function in behalf of circulation, currently being processed DOM objects

    3, $ (this), the current conversion DOM object in JQuery, a method for using jQuery

    4, the implicit conditional statement:

                var result = true return value of the conditional expression:? false return value;

    5, each element of each (function) objects do the operation.

    Collection: jQuery style. https://www.layui.com/demo/rate.html

Common methods:

    1. Filter:

    Next ( 'filters') at a current

    The current back nextAll ( 'filters') all

    nextUntil ( 'filters') from the next, to meet the 'filters' previous label,

    A current PREV ( 'filters')

    prevAll ( 'filters') ahead of the current position of all of the peer tags

    prevUntil ( 'filters') from the one to meet the 'filters' previous tag

    parent ( 'filters') parent tag

    parents ( 'filter conditions') has been looking up, until html

    parentsUntil ( 'filter conditions') has been found up 'to meet the filter criteria of the label'

    Children ( 'filters') sub-tab

    SIBLINGS ( 'filters') in addition to their own, other Brothers label

    find ( 'filter conditions') through all the tags contain their own to find 'all tags qualifying'

    first () results in the first

    last () results in the last

    Listed eq (value) / eq ( 'value') results in the first several values ​​of


    2, the content method:

        text () value / assignment and parameter acquiring text content; text ( 'this a text'), the assignment

        HTML () value / assignment and parameter acquiring text content; text ( '<p> this is a html </ p>'), the assignment

        val () input label value / assignment and parameter obtaining value; val ( 'value the new value'), the assignment. jQuery version 3 before, checkbox and radio will be out of sync, you must use the prop        

        prop (property, value) or returns the properties and values ​​of the selected element. Using simultaneous multi-value dictionary, setting: prop ( 'checked', 'checked'), getting a property value: prop ( 'checked'), undefine a result, no representative of this property.

        attr (property, value) and the value of the attribute of the selected element. Dictionary acceptable value.

        prop differs attr: add property prop for the inherent attributes attr HTML element itself with respect to our custom HTML elements in the label.  

        True and false attribute has two properties, such as checked, selected or disabled using prop ()

       

    $ ( "img") attr ( "width", function (n, v) {\\ n in the index of the current object in the filter, v is to obtain the value of width.. 
      return V-50; 
    }); 
    
    <IMG src = 'https: //static2.51cto.com/51cto/cms/homepage/2015/images/logo.gif' width = '500px' />

                    

    3, style methods:

        hasClass ( 'style name') comprising determining whether the style name

        addClass ( 'the style name'): Add calss style

        removeClass ( 'the style name'): Delete the class style

        toggleClass ( 'the style name'): does not exist, add, delete exist

        

    4, document processing:

        append (htmlstring): Finally, add the contents of the specified internal label

        prepend (htmlstring): add content inside the specified tag at the top

        after (htmlstring): after a specified label at the end, outside Add

        before (htmlstring): Before the start symbol specified tag, outside Add

        remove (): Delete the current element

        empty (): Clear all sub-elements

        clone (): Returns the element html copy

      // add 
      . $ ( '# S1') the Click (function () { 
        var = S '<Li> I was new to the </ Li>'; 
        . $ ( '# Uli') After (S) 
      }) 
      / / Remove () 
      $ ( '# R1') the Click (function () {. 
      $ ( '# Uli') Remove ();.)} 
      
      // empty (); Clear all subelements 
     $ ( '# e1'). the Click (function () { 
       $ ( '# Uli') empty ();. 
     }) 
     // clone, copy id = uli element, and added to the body 
     $ ( 'body') the append ($ ( '# Uli'. ) .clone ())

    5, mouse coordinates

        scrollTop (value) Set / get the current position of the vertical scroll bar object.

        the scrollLeft (value) / acquisition service about the current scroll position of the object.

        

        offset (). left to get the current X coordinate of the upper left corner of the element

        offset (). top Gets the current Y coordinate of the upper left corner of the element

        offset ({left: 0, top: 0}) coordinates of the current element is provided

        event.x get the current mouse coordinates X

        event.y get the current mouse Y coordinates

      $(document.body).mousemove(function(){
        $('#xx').text(event.x);
        $('#yy').text(event.y);
      })
      
      $('#divmove').offset({left:100,top:100})

    6, jQuery bind four possible events.

        Direct Binding: .click

        bind binding:

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

        delegate / undelegate binding: In the jQuery1.7 .delegate () has been .on () substituted

            $('c1').delegate('a','click',function(){ .... })

            $( elements ).delegate( selector, events, data, handler );

        on / off Bind

            $( elements ).on( events, [selector], data, handler );

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

<style>
    .d1{
        height:300px;
        width:300px;
        border:1px solid sandybrown;
    }
    .d2{
        height:200px;
        width:200px;
        margin:40px 40px;
        border:1px solid rebeccapurple;
    }
</style>
<div class="d1">
    <div class="d2">
        <span>lala</span>

    </div>
</div>
<script>
    $('.d1').on('click','span',function(){
        alert($(this).text())
    })
</script>


    7, the height and width of the element:

        image.png

        height / width: Gets / sets the element height / width - high content, width

        innerHeight / innerWidth: Gets / sets the element height / width - High content \ + padding width

        outerHeight / outerWidth: Gets / sets the element height / width - high content \ + padding + border width

        outerHeight (true) / outerWidth (true): Gets / sets the element height / width - High content \ width + padding + border + margin

<style>
    #out{
        height:300px;
        width:300px;
        border:10px solid darkred;
        padding:20px;
    }
    #in{
        height:100px;
        width:100px;
        border:10px solid rebeccapurple;
        padding:5px;
        margin-top:30px;
    }
</style>
<div id="out">
    <div id="in">
        <span id="nei">
            lalalalala
        </span>
    </div>
</div>
<script>
    var height_in=$('#in').width();
    t="height:"+height_in+'<br>';
    height_in=$('#in').innerWidth();
    t=t+"height:"+height_in+'<br>';
    height_in=$('#in').outerHeight();
    t=t+"height:"+height_in+'<br>';
    height_in=$('#in').outerHeight(true);
    t=t+"height:"+height_in+'<br>';
    $('#nei').html(t);
</script>

        8, return false to prevent events

            The following procedure does not jump to the href URL

<div class="d1">
    <div class="d2">
        <a onclick="return doNot()" href="http://www.baidu.com">lala</a>
    </div>
</div>
<script>
    function doNot(){
        alert($('a').text());
        return false;
    }
</script>


        9, jquery extension

            .extend

            .fn.extend



1, the left side of the pop-up menu, click on the sub-menu appears, other hidden

    HTML

  <div id='f1'>
    <div id='m1' class='bg'>菜单一</div>
      <ul>
        <li>sub11</li>
        <li>sub12</li>
        <li>sub13</li>
      </ul>
    <div id='m2' class='bg'>菜单二</div>
      <ul>
        <li>sub21</li>
        <li>sub22</li>
        <li>sub23</li>
      </ul>
    <div id='m3' class='bg'>菜单三</div>
      <ul>
        <li>sub31</li>
        <li>sub32</li>
        <li>sub33</li>
      </ul>
  </div>

    jQuery:

  <Script> 
    $ (Document) .ready (function () {$ ( '. BG') Next () hide ()..}); // hide all labels a document has finished loading 
    $ click (( 'bg.' ). function () {$ (this) .next (). toggle (). siblings ( 'ul'). hide ()}) // click to expand, and then hide the effect point, program chain. 
  </ script>


2, the pop-up window, other window elements inoperable. Point fork Close

    CSS Styles

    .header-menu{
      display:inline-block;
      margin-right:20px;
      height:40px;
    }
    .zhezhao{
      display:none;
      position:fixed;
      left:0;
      top:0;
      right:0;
      bottom:0;
      background-color:gray;
      z-index:8;
      opacity:0.7;
    }
    .regedit{
      display:none;
      width:400px;
      height:600px;
      position:fixed;
      background:white;
      left:50%;
      top:50%;
      margin-left:-200px;
      margin-top:-300px;
      z-index:9;
    }
    .login{
      display:none;
      width:400px;
      height:400px;
      position:fixed;
      background:white;
      left:50%;
      top:50%;
      margin-left:-200px;
      margin-top:-300px;
      z-index:9;
    }
    .divouter{
      width:100%;
      background:gray;
      text-align:right;
    }
    .close_flag{
      padding-right:10px;
      padding-top:10px;
      width:30px;
    }
    .show{
      display:block;
    }


    HTML

  
  
  <!--头部banner!-->
  <div class='header'>
    <span id='regedit' name='regedit' class='header-menu'>注册</span>
    <span id='login'  name='login' class='header-menu'>登陆</span>
  </div>
  <!--遮罩!-->
  <div class='zhezhao'></div>
  <!--注册框-->
  <div class='regedit'>
    <div class='divouter'>
      <span id='hide' name='regedit' class='close_flag'>✖<span>
    </div>
  </div>
  <!--login登陆框!divouter定位X,span样式-->
  <div class='login'>
    <div class='divouter'>   
      <span id='hide' name='login' class='close_flag'>✖<span>
    </div>
  </div>

    jQuery

    // display the registration / login box 
    $ ( 'MENU-header.') The Click (function () {. 
      $ ( 'Zhezhao.'). AddClass ( 'Show');. 
      Var SH = $ (the this) .attr ( 'name '); // attribute value acquired using the secondary positioning is performed, to achieve dynamic effects. 
      var = S' '+ SH;. 
      $ (S) .addClass (' Show ');                                
    }) 
    // off the display / login box 
    . $ ( '. close_flag') the Click (function () { 
      $ ( 'zhezhao.') removeClass ( 'Show');. 
      var Hi = $ (the this) .attr ( 'name'); 
      '.' H = var Hi +; 
      $ (H) .removeClass ( 'Show'); 
    })

3, the mouse moves in and out the background color:

    HTML:

  <style>
    .header{
      background-color:#1c97f5;
      height:40px;
      width:100%;
      min-width:960px;
      margin:0 auto;
      line-height:40px;
      text-align:right;
    }
    .header-menu{
      display:inline-block;
      margin-right:20px;
      height:40px;
    }
   </style>
  <div class='header'>
    <span class='header-menu'>注册</span>
    <span class='header-menu'>登陆</span>
  </div>

    jQuery:

    $('.header-menu').mouseover(function(i,v){$(this).css({'backgroundColor':'#2550aa','color':'white'})})
    $('.header-menu').mouseout(function(i,v){$(this).css({'backgroundColor':'','color':''})})

4, TAB menu:

    HTML

  <style>
    .tab_div{
      background:gray;
      height:30px;
      width:100%;
      
    }
    .tab_div span{
      color:white;
      line-height:30px;
      display:inline-block;
      height:30px;
      padding-right:10px;
      padding-left:10px;
    }
    .tab_content{
      display:none;
      position:absolute;
      background:#dde0e3;
      width:100%;
      top:52px;
      bottom:0px;
    }
    .tab_over{
      background-color:#4e5154;
    }
    
 </style>
    <div class='tab_div'><span id='t1'>标签一</span><span id='t2'>标签二</span><span id='t3'>标签三</span>
    </div>
    <div id='tab_content'>
      <div name='t1' class='tab_content'>111111</div>
      <div name='t2' class='tab_content'>2222222</div>
      <div name='t3' class='tab_content'>333333</div>
    </div>

    jQuery

    // tab menu script, realization thousands and thousands - there is no choice Addclass, because there are problems around the definition of the class ~ 
    
      $ ( "[name = 'T1']"). Show () 
      $ ( '. tab_div'). Children () .mouseover (function () { 
        $ (the this) .addClass ( 'tab_over') SIBLINGS () removeClass ( 'tab_over');.. 
        var = $ D (the this) .addClass ( 'tab_over') attr ( '. ID '); 
        var n-= "[name ='" + D + " ']" 
        $ (.. n-) the .Show () SIBLINGS () each (function () { 
          $ (the this) .hide () 
        }) 
      }) ; 
 
    // Option two: You can delete sub-menu ID, the province more concise code ~ ~ 

      $ (the Document) .ready (function () { 
        .. $ (. "tab_div") Children () mouseOver (function (i) { 
          $ ( .. this) .addClass ( 'tab_over ') siblings () removeClass ( 'tab_over');
          $('.tab_content').eq($(this).index()).show().siblings().hide(); ') siblings () removeClass ( 'tab_over');
        })
      })

5, the dynamic effects thumbs

    html:

<style>
    #zan{
     position: relative;
     width: 30px;
     cursor:pointer;
    }
    .jiayi{
          color:red;
          position:absolute;
        }

</style>

<br><br><br><br><br><br><br><br><br><br>
<div id="zan">赞</div>

    jQuery:

<script src="jquery-1.12.4.js"></script>
<script>
    $(document).ready(function () {
        $('#zan').click(function(){
            var font_size=14;
            var top=0;
            var right=0;
            var opacity=1;
            var ta=document.createElement('span');
                        $(ta).addClass('jiayi');
            $(ta).css('font-size',font_size+'px');
            $(ta).css('top',top+'px');
            $(ta).css('right',right+'px');
            $(ta).css('opacity',opacity);
            $(ta).text('+1');
            $(this).append(ta);

            was inter = setInterval (function () {
                font_size+=1;
                top-=2;
                right-=2;
                opacity-=0.1;
                $(ta).css('font-size',font_size+'px');
                $(ta).css('top',top+'px');
                $(ta).css('right',right+'px');
                $(ta).css('opacity',opacity);
                if (opacity<0){
                    $(ta).remove();
                    clearInterval(inter);
                }
            },20)
        });
    })

</script>

6, to determine whether registration box is empty, and prompt return empty:

        Return is essentially out of a function, and returns a label to False.

        HTML

<div class='header'>
  <span id='regedit' name='regedit' class='header-menu'>注册</span>
  <span id='login'  name='login' class='header-menu'>登陆</span>
</div>
<div class='zhezhao'></div>
  <div class='regedit'>
    <div class='divouter'>
    <span id='hide' name='regedit' class='close_flag'>✖</span>
  </div>
  <div>
      <table >
          <tbody id="reg_tb">
              <tr>
                  <td>用户名:</td>
                  <td><input type="text"/></td>
                  <td></td>
              </tr>
              <tr>
                  <td>密码:</td>
                  <td><input type="text"/></td>
                  <td></td>
              </tr>
              <tr>
                  <td>确认密码:</td>
                  <td><input type="text"/></td>
                  <td>111</td>
              </tr>
              <tr>
                  <td>邮箱:</td>
                  <td><input type="text"/></td>
                  <td></td>
              </tr>
              <tr>
                  <td>电话:</td>
                  <td><input type="text"/></td>
                  <td></td>
              </tr>
              <tr>
                  <td>爱好:</td>
                  <td><input type="text"/></td>
                  <td></td>
              </tr>
          </tbody>
      </table>
      <div>
          <input type="button" id='submit' value="提交">
          <input type="button" id='cancel' value="重置">

      </div>
  </div>
</div>
<div class='login'>
  <div class='divouter'>
    <span id='hide' name='login' class='close_flag'>✖</span>
  </div>
</div>

        CSS

.tab_div span{
  color:white;
  line-height:30px;
  display:inline-block;
  height:30px;
  padding-right:10px;
  padding-left:10px;
  background-color:#4e5154;
}
table{
  width:100%
}
.close_flag{
  padding-right:10px;
  padding-top:10px;
  width:30px;
}
.header-menu{
  display:inline-block;
  margin-right:20px;
  height:40px;
}
.zhezhao{
  display:none;
  position:fixed;
  left:0;
  top:0;
  right:0;
  bottom:0;
  background-color:gray;
  z-index:8;
  opacity:0.7;
}
.regedit{
  display:none;
  width:400px;
  height:600px;
  position:fixed;
  background:white;
  left:50%;
  top:50%;
  margin-left:-200px;
  margin-top:-300px;
  z-index:9;

}
.login{
    display:none;
    width:400px;
    height:400px;
    position:fixed;
    background:white;
    left:50%;
    top:50%;
    margin-left:-200px;
    margin-top:-300px;
    z-index:9;
}
.divouter{
  width:100%;
  background:gray;
  text-align:right;
}
.close_flag{
  padding-right:10px;
  padding-top:10px;
  width:30px;
}

        jQuery

<script>
    ($('#submit').click(function(){
        var flag=true;
        var dic=[];
        $('#reg_tb').children().each(function(){
            var input_box=$(this).children().eq(1).children().eq(0).val();
            console.log(input_box);
            if (input_box.length<=0) {
                flag = false;
                $(this).children().eq(2).html('<span style="color:red">*必填项</span>');
                return flag;
            }else{
                dic.push(input_box);
                $(this).children().eq(2).html('');
            }
        });
        if (flag){
            console.log(dic);
        } 
        Return In Flag; 
    })); 
    
    
    \\ control mask 
$ (document) .ready (function ( ) {$ () next () hide ()}) 'bg.';.. // hide all labels a document has finished loading 
$ ( '. bg'). click (function () {$ (this) .next (). toggle (). siblings ( 'ul'). hide ()}) // click to expand, and then hide the effect point, chain programming. 
. $ ( '.-header MENU') mouseOver (function (I, V) {$ (the this) .css ({ 'the backgroundColor': '# 2550aa', 'Color': 'White'})}) 
$ ( ' MENU-.header '.) mouseOut (function (I, V) {$ (the this) .css ({' the backgroundColor ':' ',' Color ':' '})}) 
// display the registration / login box 
$ ( '.header-MENU') the Click (function () {. 
  $ ( 'zhezhao.'). addClass ( 'Show');. 
  var SH = $ (the this) .attr ( 'name'); 
  var S = '.' + sh;
  $('.zhezhao').removeClass('show');
  var hi=$(this).attr('name');
  var h='.'+hi;
  $(h).removeClass('show');
})



Guess you like

Origin blog.51cto.com/yishi/2431165
Recommended