1. 程式人生 > >Jquery基礎(一)

Jquery基礎(一)

4.2 aaa round next apu eat addclass 3.1 什麽

一 jQuery是什麽?

<1> jQuery由美國人John Resig創建,至今已吸引了來自世界各地的眾多 javascript高手加入其team。

<2>jQuery是繼prototype之後又一個優秀的Javascript框架。其宗旨是——WRITE LESS,DO MORE!

<3>它是輕量級的js庫(壓縮後只有21k) ,這是其它的js庫所不及的,它兼容CSS3,還兼容各種瀏覽器

<4>jQuery是一個快速的,簡潔的javaScript庫,使用戶能更方便地處理HTMLdocuments、events、實現動畫效果,並且方便地為網站提供AJAX交互。

<5>jQuery還有一個比較大的優勢是,它的文檔說明很全,而且各種應用也說得很詳細,同時還有許多成熟的插件可供選擇。

二 什麽是jQuery對象?

jQuery 對象就是通過jQuery包裝DOM對象後產生的對象。jQuery 對象是 jQuery 獨有的. 如果一個對象是 jQuery 對象, 那麽它就可以使用 jQuery 裏的方法: $(“#test”).html();

$("#test").html()    
       //意思是指:獲取ID為test的元素內的html代碼。其中html()是jQuery裏的方法 

       //
這段代碼等同於用DOM實現代碼: document.getElementById(" test ").innerHTML; //雖然jQuery對象是包裝DOM對象後產生的,但是jQuery無法使用DOM對象的任何方法,同理DOM對象也不能使用jQuery裏的方法.亂使用會報錯 //約定:如果獲取的是 jQuery 對象, 那麽要在變量前面加上$. var $variable = jQuery 對象 var variable = DOM 對象 $variable[0]:jquery對象轉為dom對象 $("#msg").html(); $("#msg")[0].innerHTML

jquery的基礎語法:$(selector).action()

三 尋找元素(選擇器和篩選器)

3.1 選擇器

3.1.1 基本選擇器

$("*")  $("#id")   $(".class")  $("element")  $(".class,p,div")

3.1.2 層級選擇器

 $(".outer div")  $(".outer>div")   $(".outer+div")  $(".outer~div")

3.1.3 基本篩選器

$("li:first")  $("li:eq(2)")  $("li:even") $("li:gt(1)")

3.1.4 屬性選擇器

 $(‘[id="div1"]‘)   $(‘["alex="sb"][id]‘)

3.1.5 表單選擇器

$("[type=‘text‘]")----->$(":text")         註意只適用於input標簽  : $("input:checked")

實例之左側菜單

技術分享
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>left_menu</title>

    <style>
          .menu{
              height: 500px;
              width: 30%;
              background-color: gainsboro;
              float: left;
          }
          .content{
              height: 500px;
              width: 70%;
              background-color: rebeccapurple;
              float: left;
          }
         .title{
             line-height: 50px;
             background-color: #425a66;
             color: forestgreen;}


         .hide{
             display: none;
         }


    </style>
</head>
<body>

<div class="outer">
    <div class="menu">
        <div class="item">
            <div class="title">菜單一</div>
            <div class="con">
                <div>111</div>
                <div>111</div>
                <div>111</div>
            </div>
        </div>
        <div class="item">
            <div class="title">菜單二</div>
            <div class="con hide">
                <div>111</div>
                <div>111</div>
                <div>111</div>
            </div>
        </div>
        <div class="item">
            <div class="title">菜單三</div>
            <div class="con hide">
                <div>111</div>
                <div>111</div>
                <div>111</div>
            </div>
        </div>

    </div>
    <div class="content"></div>

</div>
<script src="jquery-3.2.1.js"></script>
<script>
           $(".item .title").click(function () {
                $(this).next().removeClass("hide").parent().siblings().children(".con").addClass("hide");

//                $(this).next().removeClass("hide");
//                $(this).parent().siblings().children(".con").addClass("hide");
           })
</script>


</body>
</html>
View Code

實例之tab切換

技術分享
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>tab</title>
    <script>
           function tab(self){
               var index=$(self).attr("xxx");
               $("#"+index).removeClass("hide").siblings().addClass("hide");
               $(self).addClass("current").siblings().removeClass("current");

           }
    </script>
    <style>
        *{
            margin: 0px;
            padding: 0px;
        }
        .tab_outer{
            margin: 0px auto;
            width: 60%;
        }
        .menu{
            background-color: #cccccc;
            /*border: 1px solid red;*/
            line-height: 40px;
        }
        .menu li{
            display: inline-block;
        }
        .menu a{
            border-right: 1px solid red;
            padding: 11px;
        }
        .content{
            background-color: tan;
            border: 1px solid green;
            height: 300px;
        }
        .hide{
            display: none;
        }

        .current{
            background-color: darkgray;
            color: yellow;
            border-top: solid 2px rebeccapurple;
        }
    </style>
</head>
<body>
      <div class="tab_outer">
          <ul class="menu">
              <li xxx="c1" class="current" onclick="tab(this);">菜單一</li>
              <li xxx="c2" onclick="tab(this);">菜單二</li>
              <li xxx="c3" onclick="tab(this);">菜單三</li>
          </ul>
          <div class="content">
              <div id="c1">內容一</div>
              <div id="c2" class="hide">內容二</div>
              <div id="c3" class="hide">內容三</div>
          </div>

      </div>
</body>
</html>
View Code

3.2 篩選器

3.2.1 過濾篩選器

$("li").eq(2)  $("li").first()  $("ul li").hasclass("test")

3.2.2 查找篩選器

 $("div").children(".test")     $("div").find(".test")  
                               
$(
".test").next() $(".test").nextAll() $(".test").nextUntil()

$(
"div").prev() $("div").prevAll() $("div").prevUntil()

$(
".test").parent() $(".test").parents() $(".test").parentUntil()
$(
"div").siblings()

四 操作元素(屬性,css,文檔處理)

4.1 屬性操作

--------------------------屬性
$("").attr();
$("").removeAttr();
$("").prop();
$("").removeProp();
--------------------------CSS類
$("").addClass(class|fn)
$("").removeClass([class|fn])
--------------------------HTML代碼/文本/值
$("").html([val|fn])
$("").text([val|fn])
$("").val([val|fn|arr])
---------------------------
$("").css("color","red")

註意:

技術分享
<input id="chk1" type="checkbox" />是否可見
<input id="chk2" type="checkbox" checked="checked" />是否可見



<script>

//對於HTML元素本身就帶有的固有屬性,在處理時,使用prop方法。
//對於HTML元素我們自己自定義的DOM屬性,在處理時,使用attr方法。
//像checkbox,radio和select這樣的元素,選中屬性對應“checked”和“selected”,這些也屬於固有屬性,因此
//需要使用prop方法去操作才能獲得正確的結果。


//    $("#chk1").attr("checked")
//    undefined
//    $("#chk1").prop("checked")
//    false

//  ---------手動選中的時候attr()獲得到沒有意義的undefined-----------
//    $("#chk1").attr("checked")
//    undefined
//    $("#chk1").prop("checked")
//    true

    console.log($("#chk1").prop("checked"));//false
    console.log($("#chk2").prop("checked"));//true
    console.log($("#chk1").attr("checked"));//undefined
    console.log($("#chk2").attr("checked"));//checked
</script>
attr和prop

技術分享4.2 文檔處理

//創建一個標簽對象
    $("<p>")


//內部插入

    $("").append(content|fn)      ----->$("p").append("<b>Hello</b>");
    $("").appendTo(content)       ----->$("p").appendTo("div");
    $("").prepend(content|fn)     ----->$("p").prepend("<b>Hello</b>");
    $("").prependTo(content)      ----->$("p").prependTo("#foo");

//外部插入

    $("").after(content|fn)       ----->$("p").after("<b>Hello</b>");
    $("").before(content|fn)      ----->$("p").before("<b>Hello</b>");
    $("").insertAfter(content)    ----->$("p").insertAfter("#foo");
    $("").insertBefore(content)   ----->$("p").insertBefore("#foo");

//替換
    $("").replaceWith(content|fn) ----->$("p").replaceWith("<b>Paragraph. </b>");

//刪除

    $("").empty()
    $("").remove([expr])

//復制

    $("").clone([Even[,deepEven]])

技術分享4.3 css操作

CSS
        $("").css(name|pro|[,val|fn])
    位置
        $("").offset([coordinates])
        $("").position()
        $("").scrollTop([val])
        $("").scrollLeft([val])
    尺寸
        $("").height([val|fn])
        $("").width([val|fn])
        $("").innerHeight()
        $("").innerWidth()
        $("").outerHeight([soptions])
        $("").outerWidth([options])

五 事件

頁面載入
    ready(fn)  //當DOM載入就緒可以查詢及操縱時綁定一個要執行的函數。
    $(document).ready(function(){}) -----------> $(function(){})

事件處理
    $("").on(eve,[selector],[data],fn)  // 在選擇元素上綁定一個或多個事件的事件處理函數。

    //  .on的selector參數是篩選出調用.on方法的dom元素的指定子元素,如:
    //  $(‘ul‘).on(‘click‘, ‘li‘, function(){console.log(‘click‘);})就是篩選出ul下的li給其綁定
    //  click事件;

    [selector]參數的好處:
        好處在於.on方法為動態添加的元素也能綁上指定事件;如:

        //$(‘ul li‘).on(‘click‘, function(){console.log(‘click‘);})的綁定方式和
        //$(‘ul li‘).bind(‘click‘, function(){console.log(‘click‘);})一樣;我通過js給ul添加了一個
        //li:$(‘ul‘).append(‘<li>js new li<li>‘);這個新加的li是不會被綁上click事件的

        //但是用$(‘ul‘).on(‘click‘, ‘li‘, function(){console.log(‘click‘);}方式綁定,然後動態添加
        //li:$(‘ul‘).append(‘<li>js new li<li>‘);這個新生成的li被綁上了click事件
    
    [data]參數的調用:
             function myHandler(event) {
                alert(event.data.foo);
                }
             $("li").on("click", {foo: "bar"}, myHandler)

六 動畫效果

顯示隱藏

技術分享
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="jquery-2.1.4.min.js"></script>
    <script>

$(document).ready(function() {
    $("#hide").click(function () {
        $("p").hide(1000);
    });
    $("#show").click(function () {
        $("p").show(1000);
    });

//用於切換被選元素的 hide() 與 show() 方法。
    $("#toggle").click(function () {
        $("p").toggle();
    });
})

    </script>
    <link type="text/css" rel="stylesheet" href="style.css">
</head>
<body>


    <p>hello</p>
    <button id="hide">隱藏</button>
    <button id="show">顯示</button>
    <button id="toggle">切換</button>

</body>
</html>
View Code

滑動

技術分享
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="jquery-2.1.4.min.js"></script>
    <script>
    $(document).ready(function(){
     $("#slideDown").click(function(){
         $("#content").slideDown(1000);
     });
      $("#slideUp").click(function(){
         $("#content").slideUp(1000);
     });
      $("#slideToggle").click(function(){
         $("#content").slideToggle(1000);
     })
  });
    </script>
    <style>

        #content{
            text-align: center;
            background-color: lightblue;
            border:solid 1px red;
            display: none;
            padding: 50px;
        }
    </style>
</head>
<body>

    <div id="slideDown">出現</div>
    <div id="slideUp">隱藏</div>
    <div id="slideToggle">toggle</div>

    <div id="content">helloworld</div>

</body>
</html>
View Code

淡入淡出

技術分享
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="jquery-2.1.4.min.js"></script>
    <script>
    $(document).ready(function(){
   $("#in").click(function(){
       $("#id1").fadeIn(1000);


   });
    $("#out").click(function(){
       $("#id1").fadeOut(1000);

   });
    $("#toggle").click(function(){
       $("#id1").fadeToggle(1000);


   });
    $("#fadeto").click(function(){
       $("#id1").fadeTo(1000,0.4);

   });
});



    </script>

</head>
<body>
      <button id="in">fadein</button>
      <button id="out">fadeout</button>
      <button id="toggle">fadetoggle</button>
      <button id="fadeto">fadeto</button>

      <div id="id1" style="display:none; width: 80px;height: 80px;background-color: blueviolet"></div>

</body>
</html>
View Code

回調函數

技術分享
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="jquery-2.1.4.min.js"></script>

</head>
<body>
  <button>hide</button>
  <p>helloworld helloworld helloworld</p>



 <script>
   $("button").click(function(){
       $("p").hide(1000,function(){
           alert($(this).html())
       })

   })
    </script>
</body>
</html>
View Code

七 擴展方法 (插件機制)

一 用JQuery寫插件時,最核心的方兩個方法

<script>
    
$.extend(object)      //為JQuery 添加一個靜態方法。
$.fn.extend(object)   //為JQuery實例添加一個方法。


    jQuery.extend({
          min: function(a, b) { return a < b ? a : b; },
          max: function(a, b) { return a > b ? a : b; }
        });
    console.log($.min(3,4));

//-----------------------------------------------------------------------
$.fn.extend({
"print":function(){
for (var i=0;i<this.length;i++){
console.log($(this)[i].innerHTML)
}

}
});

$("p").print();
</script>

二 定義作用域

定義一個JQuery插件,首先要把這個插件的代碼放在一個不受外界幹擾的地方。如果用專業些的話來說就是要為這個插件定義私有作用域。外部的代碼不能直接訪問插件內部的代碼。插件內部的代碼不汙染全局變量。在一定的作用上解耦了插件與運行環境的依賴。

(function(a,b){return a+b})(3,5)

       (function ($) { })(jQuery);
//相當於
        var fn = function ($) { };
        fn(jQuery);

三 默認參數

定義了jQuery插件之後,如果希望某些參數具有默認值,那麽可以以這種方式來指定。

技術分享
/step01 定義JQuery的作用域
(function ($) {
    //step03-a 插件的默認值屬性
    var defaults = {
        prevId: ‘prevBtn‘,
        prevText: ‘Previous‘,
        nextId: ‘nextBtn‘,
        nextText: ‘Next‘
        //……
    };
    //step06-a 在插件裏定義方法
    var showLink = function (obj) {
        $(obj).append(function () { return "(" + $(obj).attr("href") + ")" });
    }

    //step02 插件的擴展方法名稱
    $.fn.easySlider = function (options) {
        //step03-b 合並用戶自定義屬性,默認屬性
        var options = $.extend(defaults, options);
        //step4 支持JQuery選擇器
        //step5 支持鏈式調用
        return this.each(function () {
            //step06-b 在插件裏定義方法
            showLink(this);
        });
    }
})(jQuery);
View Code

參考:http://www.cnblogs.com/xcj26/p/3345556.html

Jquery基礎(一)