introduce
jQuery: js class library for JavaScript Query assisted JavaScript development
Because it is a js class library, jQuery. XML should be introduced before use js file
Just know some key. Just look at others. If you want to use them, see the API help document
First acquaintance
introduce
JQuery object is an array of dom objects + a series of function functions provided by jQuery
For example, $(function() {}) can replace window ο nl ο ad=function (){}
1. What is a dom object?
document.getElementById()
document.getElementsByName()
document.getElementsByTagName()
document.createElement()
objects created by methods like these are Dom objects
DOM object alert:
alert(document.getElementById("btnId"))----->[object HTMLButtonElement]
2. What is a jQuery object?
the object created through the API provided by jQuery is a jQuery object
Dom objects wrapped by jQuery are also jQuery objects
the object queried through the API provided by jQuery is a jQuery object
the effect of jQuery object alert is:
alert($(document.getElementById("btnId")))----->[object Object]
3 . jQuery objects cannot use the properties and methods of DOM objects, and vice versa
4 . Interoperation of DOM and jQuery objects
1>. Converting DOM objects into jQuery objects (* focus)
DOM object first
$(DOM object) can be converted to jQuery object ($(document.getElementById("testDiv"))
2>. Convert jQuery object to dom object
jQuery object first
jQuery object [subscript] fetch the corresponding DOM object ($(document.getElementById("testDiv")) [0])
Look at the example
<script type="text/javascript"> window.onload=function (){ var $btnObj=document.getElementById("btnId"); //alert($btnObj); // dom object [object HTMLButtonElement] $btnObj.onclick=function (){ alert("js Stand alone events for"); } </script> <button id="btnId">SayHello</button>
The following code is in < script type = "text/javascript" > < / script >
$(function (){ var $btnObj=$("#btnId"); $btnObj.click(function (){ alert("jQuery Click event for") }) alert(document.getElementById("btnId"))//dom object alert($(document.getElementById("btnId")))//jQuery object })
What is' $'
Just alert directly
$(function(){ alert($); });
The page will pop up
function( selector, context ) {
// The jQuery object is actually just the init constructor 'enhanced'
return new jQuery.fn.init( selector, context, rootjQuery );
}
It can be seen that $is a function
Core function
$(function (){//Passed in as function $(function() {}); alert("Automatically called after the page is loaded"); $( " <div>"+ " <span>div-span1</span>"+ " <span>div-span2</span>"+ " </div>" ).appendTo("body"); alert($("button").length) //$("button").length --- how many buttons are there });
The passed in parameter is[function]When: this function is executed after the document is loaded ps: $(document).ready(function(){ //This is $(function() {}); Write all The passed in parameter is[HTML character string]When: creates an element node object based on this string Will create this for us html Label object The passed in parameter is[Selector string]When: find the element node object according to this string $("#id attribute value "); id selector, query label objects according to id $("Tag name"); Tag name selector to query the tag object according to the specified tag name $(".class Attribute value"); Type selector, you can class Attribute query label object The passed in parameter is[DOM object]When: will DOM The object is wrapped as jQuery Object return I'll take this dom Object to jQuery object
selector
Basic selector
$(function (){ //1. Select the element with id one $("#one") //2. Select all elements with class mini $(".mini") //3. Select all elements whose element name is div $("div") //4. Select all elements $("*") //5. Select all span elements and elements with id two $("span,#two") })
Hierarchy selector
$(document).ready(function (){ //1. Select all div elements in the body $("body div") //2. In the body, select the div sub element $("body > div") //3. Select the next div element with id one $("#one + div") //4. Select all div sibling elements after the element with id two $("#two~div") });
Basic filter selector
$(document).ready(function(){ //1. Select the first div element $("div:first") //2. Select the last div element $("div:last") //3. Select all div elements whose class is not one $("div:not(.one)") //4. Select div elements with even index values $("div:even") //5. Select div elements with odd index values $("div:odd") //6. Select div elements with index value greater than 3 $("div:gt(3)") //7. Select the div element whose index value is equal to 3 $("div:eq(3)") //8. Select div element with index value less than 3 $("div:lt(3)") //9. Select all title elements $(":header") //10. Select all elements currently executing the animation $(":animated") //11. Select the last div element that does not execute the animation $("div:not(:animated):last") });
Content filter selector
: contains(text) / / matches the element containing the given text
: empty / / matches all empty elements that do not contain child elements or text
: has(selector) / / match the element containing the element matched by the selector
: parent v / / matches all elements that contain child elements or text
$(document).ready(function(){ //1. Select div element with text 'di' $("div:contains('di')") //2. Select a div empty element that does not contain child elements (or text elements) $("div:empty") //3. Select div element with class as mini element $("div:has(.mini)") //4. Select a div element that contains child elements (or text elements) $("div:parent") });
Attribute filter selector
[attribute] / / match the element containing the given attribute
[attribute=value] / / the element matching the given attribute is a specific value
[attribute!=value] / / match all elements that do not contain the specified attribute or the attribute is not equal to the specific value
[attribute^=value] / / matching the given attribute is an element starting with some value
[attribute$=value] / / matching the given attribute is an element ending in some value
[attribute*=value] / / match the given attribute to include elements with certain values
[attrSel1][attrSel2][attrSelN] / / composite attribute selector. It is used when multiple conditions need to be met at the same time
$(function() { //1. Select the div element containing the attribute title $("div[title]") //2. Select the div element whose attribute title Value is equal to 'test' $("div[title='test']") //3. Select div elements whose attribute Title Value is not equal to 'test' (* those without attribute title will also be selected) $("div[title!='test']") //4. Select the div element whose attribute title Value starts with 'te' $("div[title^='te']") //5. Select the div element whose attribute title Value ends with 'est' $("div[title$='est']") //6. Select the div element whose attribute title Value contains' es' $("div[title*='es']") //7. First select the div element with attribute id, and then select the div element with attribute title Value containing 'es' in the result $("div[id][title*='es']") //8. Select the div element that contains the title attribute value and the title attribute value is not equal to test $("div[title][title!='test']") });
Form object properties filter
: input / / matches all input,textarea, select, and button elements
: text / / match all text boxes
: password / / matches all password input boxes
: Radio / / match all radio boxes
: checkbox / / match all checkboxes
: submit / / match all submit buttons
: image / / matches all img Tags
: reset / / all Reset buttons are matched
: button / / match all input type=button buttons
: file / / upload all input type=file files
: Hidden / / match all invisible elements display:none or input type =hidden
Properties of the form object
: enabled / / matches all available elements
: disabled / / matches all unavailable elements
: checked / / matches all the selected radio, check, and option tag objects in the drop-down list
: selected / / matches all the selected option s
$(function(){ //1. Assign value to the visible input in the form $("#btn1").click(function(){ $(":text:enabled").val("New Value"); }); //2. Assign value to invisible input in the form $("#btn2").click(function(){ $(":text:disabled").val("New Value Too"); }); //3. Get the number of selected elements in the multiple selection box, and use the size() method to get the number of elements in the selected element set $("#btn3").click(function(){ alert($(":checkbox:checked").size()) }); //4. Get the value of each selected value in multiple selection boxes $("#btn4").click(function(){ var str = ""; var eles = $(":checkbox:checked"); console.log(eles); for(var i=0;i<eles.size();i++){ str += "["+$(eles[i]).val()+"]"; } //Traversal method of jQuery /*eles.each(function (){ alert(this.value) })*/ alert(str) }); //5. Get the content selected in the drop-down box $("#btn5").click(function(){ var str = ""; //Note the special of this selector, because the option in select is the real selected item, //Therefore, the relationship between the selected selector and the select[name='test '] selector is a child parent relationship //You must select descendants according to the basic selector var els = $("select option:selected"); console.log(els); for(var i=0;i<els.size();i++){ str += "["+$(els[i]).val()+"]"; } alert(str) }); })
Element screening method
filter eq(index|-index) // Gets the element of the given index first() //Get the first element last() //Get the last element hasClass(class) // filter(expr|obj|ele|fn) //Leave matching elements is(expr|obj|ele|fn)1.6* //Judge whether it matches the given selector. As long as there is a match, it returns true has(expr|ele) //Returns the element that contains the element that matches the selector not(expr|ele|fn) //Delete elements that match the selector slice(start,[end]) // lookup children([expr]) //Returns the child element that matches the given selector closest(expr,[con]|obj|ele)1.6* // find(expr|obj|ele) //Returns a descendant element that matches a given selector next([expr]) //Returns the next sibling element of the current element nextall([expr]) //Returns all sibling elements after the current element nextUntil([exp|ele][,fil])1.6* //Returns the following elements from the current element to the specified matching element parent([expr]) //Returns the parent element parents([expr]) // parentsUntil([exp|ele][,fil])1.6* // prev([expr]) //Returns the previous sibling element of the current element prevall([expr]) //Returns all sibling elements preceding the current element prevUntil([exp|ele][,fil])1.6* //Returns the previous element from the current element to the specified matching element siblings([expr]) //Returns all sibling elements series connection add(expr|ele|html|obj[,con]) //Add the element of the selector matching add to the current jQuery object
$(document).ready(function(){ //(1)eq() selects a div element with an index value equal to 3 $("div").eq(3) //(2)first() selects the first div element $("div").first() //(3)last() selects the last div element $("div").last() //(4)filter() selects even index in div $("div").filter(":even") //(5)is() determines #one whether it is: empty or: parent //Is is used to detect whether the jq object conforms to the specified selector $("#one").is(":empty") $("#one").is(":parent") //(6)has() select the contained in div mini //has(selector) whether the selector string contains a selector $("div").has(".mini") //(7)not() select the div whose class is not one //not(selector) selects elements that are not selectors $("div").not(".one") //(8)children() selects all div child elements with class one in the body //children() selects all child elements $("body").children("div.one") //(9)find() selects all div elements with class mini in the body //find() selects all descendant elements $("body").find("div.mini") //(10)next() #one's next div //next() selects the next sibling element $("#one").next("div") //(11) All span elements after nextall() #one //nextAll() selects all the following elements $("#one").nextAll("span") //(12) Element between nextuntil() #one and span $("#one").nextUntil("span").css("background-color","#bfa") //(13)parent() . Parent element of Mini $(".mini").parent(). //(14)prev() #two's previous div $("#two").prev() //(15) Prevlall() span all previous div s $("span").prevAll("div") //(16)prevUntil() span goes forward until #one's element $("span").prevUntil("#one") //(17)siblings() #two's all sibling elements //siblings() finds all sibling elements, including the front and back $("#two").siblings() //(18)add() selects all span elements and elements with id two $("span").add("#two") .add(".mini").add("#one") });
DOM operation
DOM property operation
HTML code/text/value html([val|fn]) a.html()take out a of html value a.html(val) Give Way a of html The value becomes val text([val|fn]) a.text()take out a of text value a.text(val) Give Way a The text value of becomes val val([val|fn|arr]) a.val() take out a of val Value( input) a.val(v) set up a of value Value is v html() You can set and get the contents in the start tag and end tag similar dom attribute innerHTML text() You can set and get the text in the start label and end label similar dom attribute innerText val() You can set and get the of form items value Attribute value similar dom attribute value attribute attr(name|pro|key,val|fn) 1,a.attr('name')take out a of name Value 2 a.attr("name","username")hold a of name The value is set to username removeAttr(name) a.removeAttr('class') remove a of class attribute prop(name|pro|key,val|fn)1.6+ 1,a.prop('id') take out a of id Value 2 a.prop('id',"bj") set up a of id Value is bj removeProp(name)1.6+ a.removeProp('class') remove a of class attribute
$(function(){ $(":radio").val(["radio2"]); //Radiocheck radio2 $(":checkbox").val(["checkbox1","checkbox3"]); //Checkboxcheck checkbox1 and checkbox3 $("#multiple").val(["mul1","mul3"]); // Selected mul1 and mul3 with id multiple $("#single").val(["sin3"]) // Selected SIN3 with id single $(":radio,:checkbox").val(["radio2","checkbox1","checkbox3"]); //Radio select radio2yi and checkbox select checkbox1 and checkbox3 })
DOM addition, deletion and modification
Document processing Internal insertion appendTo(content) a.appendTo(b); hold a Add b inside Add to last prependTo(content) a.prependTo(b); hold a Add to b inside Add to front appendTo() a.appendTo(b) hold a Insert into b The end of the child element becomes the last child element prependTo() a.prependTo(b) hold a Insert into b Before all child elements, it becomes the first child element External insertion insertAfter(content) a.insertAfter(b); hold a Insert into b Behind insertBefore(content) a.insertBefore(b); hold a Insert into b In front of insertAfter() a.insertAfter(b) obtain ba insertBefore() a.insertBefore(b) obtain ab replace replaceWith(content|fn) a.replaceWith(b) hold a use b replace replaceAll(selector) a.replaceAll(b) use a Replace all b replaceWith() a.replaceWith(b) use b replace a replaceAll() a.repalceAll(b) use a Replace all b delete empty() a.empty() hold a Empty out a All elements inside are deleted remove([expr]) a.remove(b) be-all a,yes b It will be deleted a.remove()delete a empty() a.empty(); delete a What's in the label remove() a.remove(); delete a label
No example, just understand
CSS style actions
$(function(){ var $divEle = $('div:first'); //addClass() - add one or more classes (styles) to the selected element $divEle.addClass('redDiv blueBorder') //removeClass() - Deletes one or more classes from the selected element $divEle.removeClass('redDiv blueBorder') //toggleClass() - switch between adding / deleting classes for the selected element $divEle.toggleClass('blueBorder') //offset() - returns the position of the first matching element relative to the document. var pos=$divEle.offset(); //console.log(pos) $divEle.offset({//Set position top:100, left:50 }); })
event
Document loading
- jquery After the page is loaded, the browser kernel parses the page label and creates it DOM Object will be executed immediately after - Primordial js After the page is loaded, in addition to waiting for the browser kernel to be parsed and the tag to be created DOM Object, but also wait until the content required for label display is loaded - jQuery First, js It is not executed until the page is loaded - Primordial js After the page is loaded, only the last assignment function will be executed - jQuery After the page is loaded, all registered function Functions, all executed in sequence
window.onload=function (){ alert("Primordial js After the page is loaded--1") } window.onload=function (){ alert("Primordial js After the page is loaded--2") } window.onload=function (){ alert("Primordial js After the page is loaded--3") } $(function (){ alert("jquery After the page is loaded--1") }) $(function (){ alert("jquery After the page is loaded--2") }) $(function (){ alert("jquery After the page is loaded--3") })
The execution results are:
After jquery's page is loaded – 1
After the page of jquery is loaded – 2
After the page of jquery is loaded – 3
Page loading
After the native js page is loaded – 3
Event binding
click() Have reference(function function)Bind stand-alone events and trigger stand-alone events without parameters mouseover() Mouse in event mouseout() Mouse removal event bind() Bind multiple events at a time one() Ibid., but one An event will respond only once unbind() Unbind, you can unbind multiple live() It is also a binding event. You can bind all element events matched by the selector, even if the element is dynamically created later
Event Bubbling
Event bubbling: when a child event is triggered, the same event is also passed to the event of the parent element to respond -In the body of the child element event function, return false It can prevent the bubbling transmission of events
$(function(){ $("div").click(function (){ alert("I am div") }) $("span").click(function (){ alert("I am span") return false; }) }) //<div><span></span></div>
animation
basic show([speed,[easing],[fn]]) hide([speed,[easing],[fn]]) toggle([speed],[easing],[fn]) slide slideDown([spe],[eas],[fn]) slideUp([speed,[easing],[fn]]) slideToggle([speed],[easing],[fn]) Fade in and out fadeIn([speed],[eas],[fn]) fadeOut([speed],[eas],[fn]) fadeTo([[spe],opa,[eas],[fn]]) fadeToggle([speed,[eas],[fn]])
$(function(){ //show() $("#div1").show(1500,function (){ alert("show Animation complete"); }); //hide() $("#div1").hide(1500); //toggle() $("#div1").toggle(1500) //Fade fadeIn() $("#div1").fadeIn(1500); //Fade fadeOut() $("#div1").fadeOut(1500); //Fade to fadeTo() $("#div1").fadeTo(1500,0.5,function (){ alert("Has faded to 0.5") }); //Fade toggle (fadetoggle) $("#div1").fadeToggle(1000,function(){ alert("fadeToggle complete") }); })