// %s 可以是id,标签名如p、main,也可以是类名class
var a=document.getElementById('%s');
// 生成日期函数Date(),绝不要使用在文档加载之后使用 document.write()。这会覆盖该文档。

document.write(Date());
// 改变 HTML 内容
document.getElementById("p1").innerHTML="New text!";
// 改变 HTML 属性
document.getElementById(id).<attribute>=<new value>; 
// e.g:
document.getElementById("image").src="landscape.jpg";
// 改变 HTML 样式
document.getElementById(id).style.property=<new style>;
// e.g:
document.getElementById("p2").style.color="blue";
// HTML example
<h1 id="id1">My Heading 1</h1>
<button type="button" onclick="document.getElementById('id1').style.color='red'">点击这里</button>
// 在本例中,当用户在 <h1> 元素"文字"上点击时,会改变其内容:
<h1 onclick="this.innerHTML='谢谢!'">请点击该文本</h1>
// 本例从事件处理器调用一个函数:
<script>
function changetext(id)
{
id.innerHTML="谢谢!";
}
</script>
<h1 onclick="changetext(this)">请点击该文本</h1>
// display date
<button onclick="displayDate()">点击这里</button>
// 向 button 元素分配 onclick 事件:
document.getElementById("myBtn").onclick=function(){displayDate()};

// onload 和 onunload 事件
<body onload="checkCookies()">

// create HTML node
<div id="div1">
<p id="p1">这是一个段落</p>
<p id="p2">这是另一个段落</p>
</div>
<script>
var para=document.createElement("p");
var node=document.createTextNode("这是新段落。");
para.appendChild(node);
var element=document.getElementById("div1");
element.appendChild(para);
</script>

// 删除已有的 HTML 元素
<div id="div1">
<p id="p1">这是一个段落。</p>
<p id="p2">这是另一个段落。</p>
</div>

var parent=document.getElementById("div1");
var child=document.getElementById("p1");
parent.removeChild(child);

加载新文档assign(),可以用来载入终端

<html>
<head>
<script>
function newDoc()
  {
  window.location.assign("http://www.w3school.com.cn")
  }
</script>
</head>
<body>

<input type="button" value="加载新文档" onclick="newDoc()">

</body>
</html>

CDN,Content Delivery Network,引用jQuery库

// 谷歌的jQuery,CDN
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">
</script>
// JS Deliver的jQuery CDN. 经测试,速度最快
<script src="https://cdn.jsdelivr.net/jquery/3.1.1/jquery.min.js"></script>
// MS CDN
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.1.1.min.js"></script>
// 与 jQuery 不同,Prototype 没有用以取代 window.onload() 的 ready() 方法。
<script>
function myFunction()
{
$("#h01").attr("style","color:red").html("Hello jQuery")
}
$(document).ready(myFunction);
</script>

jQuery hide()

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("p").click(function(){
        $(this).hide();
    });
});
</script>
</head>
<body>
<p>If you click on me, I will disappear.</p>
<p>Click me away!</p>
<p>Click me too!</p>
</body>
</html>

jQuery Syntax

The jQuery syntax is tailor-made for selecting HTML elements and performing some action on the element(s).
Basic syntax is: $(selector).action()

A $ sign to define/access jQuery
A (selector) to "query (or find)" HTML elements
A jQuery action() to be performed on the element(s)
Examples:

$(this).hide() - hides the current element.

$("p").hide() - hides all <p> elements.

$(".test").hide() - hides all elements with class="test".

$("#test").hide() - hides the element with id="test".

Document Ready Function

$(document).ready(function(){

   // jQuery methods go here...

});

The code above is the same with below:

$(function(){

   // jQuery methods go here...

});

CSS Selector

    Selector    Example Example description CSS
    .class  .intro  Selects all elements with class="intro" 1
    #id #firstname  Selects the element with id="firstname" 1
    *   *   Selects all elements    2
    element p   Selects all <p> elements    1
    element,element div, p  Selects all <div> elements and all <p> elements 1
    element element div p   Selects all <p> elements inside <div> elements  1
    element>element div > p Selects all <p> elements where the parent is a <div> element    2
    element+element div + p Selects all <p> elements that are placed immediately after <div> elements   2
    element1~element2   p ~ ul  Selects every <ul> element that are preceded by a <p> element   3
    [attribute] [target]    Selects all elements with a target attribute    2
    [attribute=value]   [target=_blank] Selects all elements with target="_blank"   2
    [attribute~=value]  [title~=flower] Selects all elements with a title attribute containing the word "flower"    2
    [attribute|=value]  [lang|=en]  Selects all elements with a lang attribute value starting with "en" 2
    [attribute^=value]  a[href^="https"]    Selects every <a> element whose href attribute value begins with "https"    3
    [attribute$=value]  a[href$=".pdf"] Selects every <a> element whose href attribute value ends with ".pdf"   3
    [attribute*=value]  a[href*="w3schools"]    Selects every <a> element whose href attribute value contains the substring "w3schools" 3
    :active a:active    Selects the active link 1
    ::after p::after    Insert something after the content of each <p> element  2
    ::before    p::before   Insert something before the content of each <p> element 2
    :checked    input:checked   Selects every checked <input> element   3
    :disabled   input:disabled  Selects every disabled <input> element  3
    :empty  p:empty Selects every <p> element that has no children (including text nodes)   3
    :enabled    input:enabled   Selects every enabled <input> element   3
    :first-child    p:first-child   Selects every <p> element that is the first child of its parent 2
    ::first-letter  p::first-letter Selects the first letter of every <p> element   1
    ::first-line    p::first-line   Selects the first line of every <p> element 1
    :first-of-type  p:first-of-type Selects every <p> element that is the first <p> element of its parent   3
    :focus  input:focus Selects the input element which has focus   2
    :hover  a:hover Selects links on mouse over 1
    :in-range   input:in-range  Selects input elements with a value within a specified range    3
    :invalid    input:invalid   Selects all input elements with an invalid value    3
    :lang(language) p:lang(it)  Selects every <p> element with a lang attribute equal to "it" (Italian) 2
    :last-child p:last-child    Selects every <p> element that is the last child of its parent  3
    :last-of-type   p:last-of-type  Selects every <p> element that is the last <p> element of its parent    3
    :link   a:link  Selects all unvisited links 1
    :not(selector)  :not(p) Selects every element that is not a <p> element 3
    :nth-child(n)   p:nth-child(2)  Selects every <p> element that is the second child of its parent    3
    :nth-last-child(n)  p:nth-last-child(2) Selects every <p> element that is the second child of its parent, counting from the last child  3
    :nth-last-of-type(n)    p:nth-last-of-type(2)   Selects every <p> element that is the second <p> element of its parent, counting from the last child    3
    :nth-of-type(n) p:nth-of-type(2)    Selects every <p> element that is the second <p> element of its parent  3
    :only-of-type   p:only-of-type  Selects every <p> element that is the only <p> element of its parent    3
    :only-child p:only-child    Selects every <p> element that is the only child of its parent  3
    :optional   input:optional  Selects input elements with no "required" attribute 3
    :out-of-range   input:out-of-range  Selects input elements with a value outside a specified range   3
    :read-only  input:read-only Selects input elements with the "readonly" attribute specified  3
    :read-write input:read-write    Selects input elements with the "readonly" attribute NOT specified  3
    :required   input:required  Selects input elements with the "required" attribute specified  3
    :root   :root   Selects the document's root element 3
    ::selection ::selection Selects the portion of an element that is selected by a user     
    :target #news:target    Selects the current active #news element (clicked on a URL containing that anchor name) 3
    :valid  input:valid Selects all input elements with a valid value   3
    :visited    a:visited   Selects all visited links   1

关于w3school

w3school.com.cn是国内的(据说是抄袭国外网站),w3school.com是宣传圣经的,w3schools.com才是最正宗的在线教学网站。

oop中,对象的属性是什么?what's attribute of object?

objectName.propertyName. What's the difference between property and attribute?

jQuery中$符号的意义

That said, there is one caveat: by default, jQuery uses $ as a shortcut for jQuery.
为了防止解决冲突,

<!-- Putting jQuery into no-conflict mode. -->
<script src="prototype.js"></script>
<script src="jquery.js"></script>
<script>

var $j = jQuery.noConflict();
// $j is now an alias to the jQuery function; creating the new alias is optional.

$j(document).ready(function() {
    $j( "div" ).hide();
});

// The $ variable now has the prototype meaning, which is a shortcut for
// document.getElementById(). mainDiv below is a DOM element, not a jQuery object.
window.onload = function() {
    var mainDiv = $( "main" );
}

</script>

jQuery Tricks

// Moving elements using different approaches.

// Make the first list item the last list item:
var li = $( "#myList li:first" ).appendTo( "#myList" );

// Another approach to the same problem:
$( "#myList" ).append( $( "#myList li:first" ) );

// Note that there's no way to access the list item
// that we moved, as this returns the list itself.

// Making a copy of an element.

// Copy the first list item to the end of the list:
$( "#myList li:first" ).clone().appendTo( "#myList" );
// If you need to copy related data and events, be sure to pass true as an argument to .clone().

// remove()
.remove() and .detach() and .empty()

// Creating new elements from an HTML string.
$( "<p>This is a new paragraph</p>" );
$( "<li class=\"new\">new list item</li>" );
// Creating a new element with an attribute object.
$( "<a/>", {
    html: "This is a <strong>new</strong> link",
    "class": "new",
    href: "foo.html"
});
// Getting a new element on to the page.

var myNewElement = $( "<p>New element</p>" );

myNewElement.appendTo( "#content" );

myNewElement.insertAfter( "ul:last" ); // This will remove the p from #content!

$( "ul" ).last().after( myNewElement.clone() ); // Clone the p so now we have two.

var myItems = [];
var myList = $( "#myList" );

for ( var i = 0; i < 100; i++ ) {
    myItems.push( "<li>item " + i + "</li>" );
}

myList.append( myItems.join( "" ) );
// Using a function to determine an attribute's new value.
$( "#myDiv a:first" ).attr({
    rel: "nofollow",
    href: function( idx, href ) {
        return "/new/" + href;
    }
});

$( "#myDiv a:first" ).attr( "href", function( idx, href ) {
    return "/new/" + href;
});


// Manipulating multiple attributes.
$( "#myDiv a:first" ).attr({
    href: "newDestination.html",
    rel: "nofollow"
});

// Manipulating a single attribute.
$( "#myDiv a:first" ).attr( "href", "newDestination.html" );


// Inserting a new element after another with the native DOM API.

var target = document.getElementById( "target" );

var newElement = document.createElement( "div" );

target.parentNode.insertBefore( newElement, target.nextSibling );

// Inserting a new element after another with jQuery.

var target = document.getElementById( "target" );

var newElement = document.createElement( "div" );

$( target ).after( newElement );

// Selecting only the first <h1> element on the page (in a jQuery object)

var headings = $( "h1" );

var firstHeading = headings.eq( 0 );
// Selecting only the first <h1> element on the page.

var firstHeadingElem = $( "h1" ).get( 0 );
// Selecting only the first <h1> element on the page (alternate approach).

var firstHeadingElem = $( "h1" )[ 0 ];
// Creating two jQuery objects for the same element.

var logo1 = $( "#logo" );
var logo2 = $( "#logo" );
// Comparing jQuery objects.

alert( $( "#logo" ) === $( "#logo" ) ); // alerts "false"
// Comparing DOM elements.

var logo1 = $( "#logo" );
var logo1Elem = logo1.get( 0 );

var logo2 = $( "#logo" );
var logo2Elem = logo2.get( 0 );

alert( logo1Elem === logo2Elem ); // alerts "true"


<div class="grandparent">
    <div class="parent">
        <div class="child">
            <span class="subchild"></span>
        </div>
    </div>
    <div class="surrogateParent1"></div>
    <div class="surrogateParent2"></div>
</div>
// Selecting an element's direct parent:

// returns [ div.child ]
$( "span.subchild" ).parent();

// Selecting all the parents of an element that match a given selector:

// returns [ div.parent ]
$( "span.subchild" ).parents( "div.parent" );

// returns [ div.child, div.parent, div.grandparent ]
$( "span.subchild" ).parents();

// Selecting all the parents of an element up to, but *not including* the selector:

// returns [ div.child, div.parent ]
$( "span.subchild" ).parentsUntil( "div.grandparent" );

// Selecting the closest parent, note that only one parent will be selected
// and that the initial element itself is included in the search:

// returns [ div.child ]
$( "span.subchild" ).closest( "div" );

// returns [ div.child ] as the selector is also included in the search:
$( "div.child" ).closest( "div" );


CSS, Styling, & Dimensions

// Getting CSS properties.

$( "h1" ).css( "fontSize" ); // Returns a string such as "19px".

$( "h1" ).css( "font-size" ); // Also works.
// Setting CSS properties.

$( "h1" ).css( "fontSize", "100px" ); // Setting an individual property.

// Setting multiple properties.
$( "h1" ).css({
    fontSize: "100px",
    color: "red"
});

// Working with classes. class是在

var h1 = $( "h1" );

h1.addClass( "big" );
h1.removeClass( "big" );
h1.toggleClass( "big" );

if ( h1.hasClass( "big" ) ) {
    ...
}

// Basic dimensions methods.

// Sets the width of all <h1> elements.
$( "h1" ).width( "50px" );

// Gets the width of the first <h1> element.
$( "h1" ).width();

// Sets the height of all <h1> elements.
$( "h1" ).height( "50px" );

// Gets the height of the first <h1> element.
$( "h1" ).height();


// Returns an object containing position information for
// the first <h1> relative to its "offset (positioned) parent".
$( "h1" ).position();

Question? what's data() use?

// Storing and retrieving data related to an element.

$( "#myDiv" ).data( "keyName", { foo: "bar" } );

$( "#myDiv" ).data( "keyName" ); // Returns { foo: "bar" }
// Storing a relationship between elements using .data()

$( "#myList li" ).each(function() {

    var li = $( this );
    var div = li.find( "div.content" );

    li.data( "contentDiv", div );

});

// Later, we don't have to find the div again;
// we can just read it from the list item's data
var firstLi = $( "#myList li:first" );

firstLi.data( "contentDiv" ).html( "new content" );
// Doesn't work:
$( "input" ).val( $( this ).val() + "%" );

// .val() does not change the execution context, so this === window
$( "input" ).each( function( i, el ) {
    var elem = $( el );
    elem.val( elem.val() + "%" );
});
// This doesn't work; text() returns a string, not the jQuery object:
$( this ).find( "li a" ).eq( 2 ).text().replace( "foo", "bar" );

// This works:
var thirdLink = $( this ).find( "li a" ).eq( 2 );

var linkText = thirdLink.text().replace( "foo", "bar" );

thirdLink.text( linkText );
// Event setup using the `.on()` method with data
$( "input" ).on(
    "change",
    { foo: "bar" }, // Associate data with event binding
    function( eventObject ) {
        console.log("An input value has changed! ", eventObject.data.foo);
    }
);

// Tearing down a particular click handler, using a reference to the function
var foo = function() { console.log( "foo" ); };
var bar = function() { console.log( "bar" ); };

$( "p" ).on( "click", foo ).on( "click", bar );
$( "p" ).off( "click", bar ); // foo is still bound to the click event


Event

<button id="helloBtn">Say hello</button>
// Event binding using addEventListener
var helloBtn = document.getElementById( "helloBtn" );

helloBtn.addEventListener( "click", function( event ) {
    alert( "Hello." );
}, false );

// Event binding using a convenience method
$( "#helloBtn" ).click(function( event ) {
    alert( "Hello." );
});

// The many ways to bind events with jQuery
// Attach an event handler directly to the button using jQuery's
// shorthand `click` method.
$( "#helloBtn" ).click(function( event ) {
    alert( "Hello." );
});

// Attach an event handler directly to the button using jQuery's
// `bind` method, passing it an event string of `click`
$( "#helloBtn" ).bind( "click", function( event ) {
    alert( "Hello." );
});

// As of jQuery 1.7, attach an event handler directly to the button
// using jQuery's `on` method.
$( "#helloBtn" ).on( "click", function( event ) {
    alert( "Hello." );
});

// As of jQuery 1.7, attach an event handler to the `body` element that
// is listening for clicks, and will respond whenever *any* button is
// clicked on the page.
$( "body" ).on({
    click: function( event ) {
        alert( "Hello." );
    }
}, "button" );

// An alternative to the previous example, using slightly different syntax.
$( "body" ).on( "click", "button", function( event ) {
    alert( "Hello." );
});

// Preventing a default action from occurring and stopping the event bubbling
$( "form" ).on( "submit", function( event ) {

    // Prevent the form's default submission.
    event.preventDefault();

    // Prevent event from bubbling up DOM tree, prohibiting delegation
    event.stopPropagation();

    // Make an AJAX request to submit the form data
});

what's the function delegated events does?

Triggering Event Handlers

// This will not change the current page
$( "a" ).trigger( "click" );
// Triggering a native browser event using the simulate plugin
$( "a" ).simulate( "click" );
// Triggering an event handler the right way
var foo = function( event ) {
    if ( event ) {
        console.log( event );
    } else {
        console.log( "this didn't come from an event!" );
    }
};

$( "p" ).on( "click", foo );

foo(); // instead of $( "p" ).trigger( "click" )
$( document ).on( "myCustomEvent", {
    foo: "bar"
}, function( event, arg1, arg2 ) {
    console.log( event.data.foo ); // "bar"
    console.log( arg1 );           // "bim"
    console.log( arg2 );           // "baz"
});

$( document ).trigger( "myCustomEvent", [ "bim", "baz" ] );

Cross-Origin Resource Sharing (CORS)
JSONP (JSON with Padding)
Ajax (Asynchronous JavaScript and XML)
XMLHttpRequest (XHR)

AJAX code show

// Using the core $.ajax() method
$.ajax({

    // The URL for the request
    url: "post.php",

    // The data to send (will be converted to a query string)
    data: {
        id: 123
    },

    // Whether this is a POST or GET request
    type: "GET",

    // The type of data we expect back
    dataType : "json",
})
  // Code to run if the request succeeds (is done);
  // The response is passed to the function
  // function括号内的变量是这个jQuery语句前面生成的成员变量,代表自己调用前callback
  .done(function( json ) {
     $( "<h1>" ).text( json.title ).appendTo( "body" );
     $( "<div class=\"content\">").html( json.html ).appendTo( "body" );
  })
  // Code to run if the request fails; the raw request and
  // status codes are passed to the function
  .fail(function( xhr, status, errorThrown ) {
    alert( "Sorry, there was a problem!" );
    console.log( "Error: " + errorThrown );
    console.log( "Status: " + status );
    console.dir( xhr );
  })
  // Code to run regardless of success or failure;
  .always(function( xhr, status ) {
    alert( "The request is complete!" );
  });

  // Using jQuery's Ajax convenience methods

// Get plain text or HTML
$.get( "/users.php", {
    userId: 1234
}, function( resp ) {
    console.log( resp ); // server response
});

// Add a script to the page, then run a function defined in it
$.getScript( "/static/js/myScript.js", function() {
    functionFromMyScript();
});

// Get JSON-formatted data from the server
$.getJSON( "/details.php", function( resp ) {

    // Log each key in the response data
    $.each( resp, function( key, value ) {
        console.log( key + " : " + value );
    });
});


load()

The .load() method is unique among jQuery’s Ajax methods in that it is called on a selection. The .load() method fetches HTML from a URL, and uses the returned HTML to populate the selected element(s). In addition to providing a URL to the method, you can optionally provide a selector; jQuery will fetch only the matching content from the returned HTML.

// Using .load() to populate an element
$( "#newContent" ).load( "/foo.html" );
// Using .load() to populate an element based on a selector
$( "#newContent" ).load( "/foo.html #myDiv h1:first", function( html ) {
    alert( "Content updated!" );
});

Cross-Origin Resource Sharing (CORS)
off guard 措手不及
imperative 迫切的
terse 简短的
可选的 callback 参数是请求成功后所执行的函数名。

Responses can only be handled using a callback
what's the definition of response and callback?

$.get( "foo.php", function( response ) {
    console.log( response ); // server response
});