jQuery

  1. jQuery basics: http://jqfundamentals.com/chapter/jquery-basics
  2. $(): can take these things:
    • CSS selectors
    • HTML
    • JavaScript Object
  3. jQuery select elements the same way CSS does
  4. Direct to another page:
    $('button selector').click(function(){
       document.location.href='the_link_to_go_to.html';
    })
  5. Example:
    $("#myTop").css({"background-color","blue"});
    // set multiple attributes:
    css({"propertyname":"value","propertyname":"value",...});
  6. text(): When this method is used to return content, it returns the text content of all matched elements (HTML markup will be removed). When this method is used to set content, it overwrites the content of ALL matched elements.
  7. Binding an event:
    $("element").click(function(){
      alert($(this).text());
    });
    // for elements existed already
    $("element").bind('click', function(){
      alert($(this).text());
    })

    jQuery events: form; document loading, browser, mouse, keyboard

  8. You can call document.ready multiple times, and jQuery will chain together each one to be called in succession.
  9. unbind: In the simplest case, with no arguments,.unbind() removes all handlers attached to the elements
    $("myElement").bind("click", function(){
        alert("something");
    })
    
    $("myElement").unbind("click");
    // or 
    $("myElement").unbind(); // unbind all element events
  10. n-th child selector: things start at 1 other than 0:
    $("document").ready(function(){
        $("ul li:nth-child(2n)").css('border', '2px solid red');
    }); // n start counting at 1
  11. The $.contains() method returns true if the DOM element provided by the second argument is a descendant of the DOM element provided by the first argument, whether it is a direct child or nested more deeply. Otherwise, it returns false. Only element nodes are supported; if the second argument is a text or comment node, $.contains() will return false.
  12. this and $(this): this is a keyword of javascript, $(this) is wrapped with jquery, so it has jquery properties and methods like $(this).attr('id') which equals this.getElementById();
  13. If you don't tell a function what value to return, it will return a value of
  14. .before methods insert content before the specified element:
    $("button").click(function(){
      $("p").before("<p>Hello world!</p>");
    });
  15. length property, size(), get() function:
    var elems = $("p").length; //  equals $("p").size()
    // get(), will return an array of DOM elements instead of jQuery wrapped array
    var elems2 = $("li").get(); // get() method can specify the index of the outcome: $("li").get(0);
    $('ul').find('li.b').css('border', '3px solid red'); // find <li> item inside <ul> which have b class
    $('p').each(function(){
    // code to proceed
    });
  16. .hover(handlerIn(eventObject), handlerOut(eventObject)): the two arguments are of type function, which is executed when mouse enters or leaves.
  17. remove() and detach(), empty(): remove will delete the DOM element, and detach will hold on to it and can restore for you later. empty() method removes the contents of selected elements: $("p").empty();
  18. Traversal: .parent(), .children([selector]), .prev(), .next(): .children() do not return text node. parents() returns parents of selected elements. siblings() return all same level DOM elements except itself. children() select next level of DOM.
  19. Arrays don’t have to start with a dollar sign ($). The practice of indicating a jQuery array with a dollar sign is a coding convention of jQuery developers. 
  20. $(selector).replaceWith(content) method, one-to-one exchange: 
  21. before and after methods:
    $('.meat').before('<li>tofu</li>');
    $('.meat').after('<li>tofu</li>');
  22. filter methods:
    • first: $('menu_list').children().first();
    • last: $('menu_list').children().last();
    • eq: $('menu_list').children().eq(0); // first element
    • slice: keep elements between given index(exclusive both ends), $('menu_list').children().slice(1,3); returns the second one
    • filter: keep matched elements of the selector, 
    • not: filter out everything that does not match the selector
  23. fadeIn, fadeOut, fadeTo(lets you animate the selected element to a specific opacity percentage); slideUp, slideDown, slideToggle;
    // fadeIn syntax: $(selector).fadeIn(speed,callback);
    $("lightning").fadeIn('fast"); // string of slow, normal, fast
    $("lightning").fadeIn(1000); // milliseconds
    // default speed is normal, which is 0.4 seconds
  24. animate: this method only work on CSS properties that use numbers for their settings:
    // syntax: $("selector").animate(property [,duration][,easing][,callback])
    $("#my_div").animate({left:"100px"}, 500); // the first parameter is required while the second is optional, the first part is // the CSS property you want to animate, the second is duration
    $("#my_div").animate({
    opacity:0,
    "200px",
    height:"800px"
    }, 500) // you can set multiple at one time

  25. relative operator: 
    $("#box").animate({left:"+=20"})
  26. Disable animation: jQuery.fx.off
    <body>
      <p><input type="button" value="Run"/> <button>Toggle fx</button></p>
    <div></div>
    <script>
    var toggleFx = function() {
      $.fx.off = !$.fx.off;
    };
    toggleFx();
     
    $("button").click(toggleFx)
     
    $("input").click(function(){
      $("div").toggle("slow");
    });
      </script>
    </body>
  27. Difference between DOM standards and CSS standards: http://www.oxfordu.net/webdesign/dom/straight_text.html
  28. Object constructor:
    function MyPerson(a, b){
      this.name = a;
      this.age = b;
    }
    var myperson = new MyPerson('Jo', 14);
  29. Create element:
    var newItem = $("<p>This is a paragraph</p>");
    $("#para2").html(newItem); // .html() grabs the first match item and return or change the content, similar method is .text()
  30. Manipulating attributes:
    1 attr(name)  // accesses property on the first matched element
    2 attr(properties) // sets a series of attributes on all matched elements, for example
    3 attr({src:"images/img.jpg", alt:"some text"})
    4 attr(key, value) // set value to an attribute
    5 attr(key, fn)
    6 removeAttr(name)
    $(document).ready(
    $("a").attr("target", "_blank"); // access all links and open it in new window
    )
  31. $.inArray: return the index of a value, -1 if not found:
    var index = $.inArray(value, array);
    // var index = $.inArray('needle', haystack);
  32. To empty an array you just need to set the length to 0:
    var used_cards = new Array('needle', 'heel', 'hello');
    used_cards.length = 0;
  33. window object is the topmost object of the javascript world. It has methods and properties:
    window.name // a property let us set or access the name of the window
    window.history // a property that let us access the different URLs loaded over time
    window.document // a property refers to the main content of the loaded document
    window.onfocus // detects the current active window
    window.onblur // when window loses focus
    window.setTimeout(); window.clearTimeout(); window.setInterval();
    window.clearInterval();
  34. Inserting content:
  35. CSS:
    addClass(class)  // adds the specified class to each of the set of matched elements
    hasClass(class) // returns true if the specified class is present on at least one of the set of matched elements
    removeClass(class);
    toggleClass(class) // Adds the specified class if it is not present, removes the specified class if present
    toggleClass(class, switch) // Adds the specified class if switch is true, otherwise removes the class
  36. window.onblur, window.onfocus:
    $("document").ready(
      window.onblur = blurMe;
      window.onfocus = focusMe;
      function blurMe(){
        // code;
      }
      // code
    )
  37. setTimeout, clearTimeout, setInterval, clearInterval(javascript methods); delay()(jQuery method):
    setTimeout(myFunction, 4000); // wait some time until ...
    setInterval(repeatMe, 1000);  // repeat after some time
    slideDown().delay(5000).slideUp(); // pause between effects that are queued up in a chain of effects
    // use clearInterval to clear repeated effects:
    myInterval = setInterval(repeatMe, 4000);
    clearInterval(myInterval);
    Notice: setTimeout and setInterval are methods specific to window object, but they can be called without window prefix
  38. Math.random() : produces [0, 1)
  39. jQuery variable:
    .click(function(){
        var $this = $( this );
    });

    $this is a jQuery variable, $ make it a notation for jQuery variable(wrapper)

  40. get time:
    function getTime(){
            var a_p = "";
            var d = new Date();
            var curr_hour = d.getHours();
            
            (curr_hour < 12) ? a_p = "AM" : a_p = "PM";
            (curr_hour == 0) ? curr_hour = 12 : curr_hour = curr_hour;
            (curr_hour > 12) ? curr_hour = curr_hour - 12 : curr_hour = curr_hour;
            
            var curr_min = d.getMinutes().toString();
            var curr_sec = d.getSeconds().toString();
            
            if (curr_min.length == 1) { curr_min = "0" + curr_min; }
            if (curr_sec.length == 1) { curr_sec = "0" + curr_sec; } 
            
            $('#updatedTime').html(curr_hour + ":" + curr_min + ":" + curr_sec + " " + a_p );
        }
  41. .load(): pass into it URL to insert into the specified element:
    $("#feeds").load("feeds.html");

    http://api.jquery.com/load/

  42. $() is short for $(document).ready();
  43. test element:
    if ( $( '#nonexistent' ).length ) {
      // This code will only run if there's a matching element
    }
    if ( $( '#nonexistent' ) ) {
      // Wrong! This code will always run!
    }
  44. Getters, SettersThere are many methods you can call once you've made a selection. These methods generally fall into two categories: getters and setters. Getters retrieve a piece of information from the selection, and setters alter the selection in some way. In almost all cases, getters operate only on the first element in a selection (.text() is a notable exception); setters operate on all elements in a selection, using what's known as implicit iteration.
  45. ajax:
    • $.get
    • $.getJSON
    • $.getScript
    • $.post
    • $.load
  1. n
  2. n
原文地址:https://www.cnblogs.com/wade-case/p/3189312.html