JQuery
jQuery is an excellent javascript library after Prototype and is an open source project. With simple syntax and cross-platform compatibility, jQuery greatly simplifies javaScript developers traversing html documents, manipulating Doms, handling events, executing animations, and developing ajax operations. Its unique and elegant code style changes the way Javascript programmers design and write programs.
*******************
In order to use JQuery, we need to download a JQuery library file from the official (jquery.com). We download the latest uncompressed version of jquery-1.3.2.js
You don't need to install Jquery, just put the downloaded library file in a public place on the website. When we want to use Jquery on a page, we simply need to reference the location of the library file in the relevant html document. Such as:
<script src="jquery-1.3.2.js" type="text/javascript"></script>
Note that the <script> tag that references the JQuery library file must be placed before the <script> tag of the page definition javascript. Otherwise, the code we write will not reference the Jquery framework.
******************
<body onload="emphasize();">
The above statement will be executed after the page is loaded. Jquery allows us to use $(document).ready(). By using this method, you can call the function you are binding immediately when the DOM is ready to be read and manipulated.
The above statement can be written as:
$(document).ready(emphasize);
However, the defined function emphasize() is only used once at load time, so it takes up an identifier in the namespace. Javascript has an anonymous function. We can do this;
$(document).ready(function(){
....
});
$(document).ready() is executed after all the dom elements on the page have been loaded (including the struts tag).
E.g:
<HTML>
<HEAD>
<style type="text/css">
</style>
<script src="jquery.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
// will output the test string when the page loads.
Document.writeln("test");
});
</script>
</HEAD>
<BODY>
</BODY>
</HTML>
1 factory function $()
In JQuery, no matter which type of selector we use (css, xpath, or custom selector), we start with a dollar sign and a pair of parentheses.
The $() function eliminates the need to use a for() loop to access a set of elements, because any element placed in parentheses will automatically loop through and be saved to a JQuery object. There are almost no restrictions on the parameters that can be used in parentheses in the $() function.
Commonly used as follows:
Tag name: $(‘p‘) will get all the paragraphs in the document.
ID: $(‘#some-id‘) will get an element in the document with the corresponding some-id ID. Id can also be the value of a variable jQuery("#"+selectArray[i]).length
Class: $(‘.some-class‘) will get all the elements of the document with some-class classes.
The tag name selector is used in conjunction with the css class selector:
$(‘#some-id.some-class‘) represents an element that takes id=som-id with some-class.
For example: $(‘#button1.class1‘)
Tag name and ID combined
$(‘#some-id tagname ‘) means to get the same tag element in the id=some-id that is the same for the given tag name. The id and tag name are separated by a space. E.g:
$("#alltrade select option:selected")
$("*"), which means that all elements are matched.
Note that multiple tag names are used together as selectors separated by spaces.
$(‘table tbody tr:odd‘);// means that <trbody> under <table> is <tr> is an odd number of lines.
$(‘table tbody tr:even‘).addClass(‘even‘);// means that <trbody> under <table> is <tr> is an even number of lines.
2CSS selector
JQuery supports most of the selectors in CSS Specification 1 through Specification 3. This support for CSS selectors allows developers to enhance their websites without worrying about which browsers do not understand advanced selectors. You, as long as the browser has Javascript enabled.
.addClass() and .removeClass() methods
The role of the .addClass() method in Jquery is to apply the Css class to the portion of the page we select. The only argument to the .addClass and .removeClass() methods is to add the Css class name.
3XPath selector
XPath (XML Path Language) is a language that identifies different elements or element values in an XML document. JQuery supports a set of basic XPath selectors, and in JQuery, XPath and Css selectors can be used regardless of the type of document.
When designing the property selector, Jquery uses the conventions in XPath to identify the property, placing the property in front of the parentheses. For example, to select all links with the title attribute, you can use the following code:
$(‘a[title]‘)
Can be used to specify an element that is contained in another element. For example, we can get all the div elements that contain an ol element with the following selector expression.
$(‘div:has(ol)‘)
Add style to the link
The attribute selector allows you to identify the matching string start position and the matching string end position in a syntax similar to a regular expression. Also, you can use an asterisk (*) to indicate any position of the string. For example, in the following example, the <a> link with the href attribute and the value of href that starts with mailto: is displayed in gray.
<HTML>
<HEAD>
<style type="text/css">
A.mailto{color:#cccccc;}//gray
</style>
<script src="jquery.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
/ / The <a> link with the href attribute and the value of href as the beginning of mailto: is displayed in gray.
$("a[href^=‘mailto:‘]").addClass(‘mailto‘);
});
</script>
</HEAD>
<BODY>
<a href="mailto:hebinbin71722@126.com">email</a>
</BODY>
</HTML>
4 custom selectors
In addition to CSS and XPath selectors, Jquery adds unique and completely different custom selectors. Most of the custom selectors in Jquery allow us to select specific elements based on a certain standard. Custom selectors start with a colon (:). For example, if we want to select 2 items from a matching div collection with a horizontal class, we should use the following code:
$(‘div.horizontal:eq(1)‘}
Note that since the javaScript sequence is numbered starting from 0, eq(1) takes the second element in the collection.
Two very useful custom selectors in the Jquery library are: odd and :even. Here we use:odd and :even to add a light blue background to the even rows of a table, and add a light yellow background to the odd rows. The :odd and :even selectors use the numbering of javascript itself starting from 0, so the first row of the table is numbered 0 (even), and the second row of the table is numbered 1 (odd).
<HTML>
<HEAD>
<style type="text/css">
*.odd{background-color:#ffffcc;}//Light blue background.
*.even{background-color:#cceeff;}//Light yellow background.
</style>
<script src="jquery.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
$(‘tr:odd‘).addClass(‘odd‘);//Just if the label is named tr and is an even line, use a light blue background
$(‘tr:even‘).addClass(‘even‘);//Just if the label is named tr and is an odd line, use a light yellow background
});
</script>
</HEAD>
<BODY>
<table>
<tr>
<td>As You Like It</td>
<td>Comedy</td>
</tr>
<tr>
<td>All‘s Well</td>
<td>Comedy</td>
</tr>
<tr>
<td>Hamlet</td>
<td>Tragedy</td>
</tr>
</table>
</BODY>
</HTML>
:contains(‘String‘) is used to match elements that contain the content of a given text. For example: $("td:contains(‘Comedy‘)") is used to match the elements of <td> that contain Comedy.
:empty, matches all empty elements that do not contain child elements or text. Such as: $ ("td:empty"); will match such td:
<td></td> (empty elements that do not contain child elements or text)
:parent, as opposed to :empty, which matches elements that contain child elements or text.
:has(selector), which matches the element containing the element that the selector matches. E.g:
$("div:has(p)")// is used to match divs containing <p> elements in <div> elements
:not(selector), removes all elements that match a given selector.
:eq(index), which matches an element with a given index value index. Such as $("tr:eq(1)")
:gt(index), matches all elements larger than the given index value, such as $("tr:gt(1)")
:lt(index), matches all elements that are less than the given index value, such as $("tr:lt(1)")
:even, the matching index value is an even element, counting from 0.
:odd, the matching index value is an odd number of elements, counting from 0.
:first, matches the first element found
:last, matches the last element found.
:header, matching title elements like h1, h2, h3
:visible, matches all visible elements
:hidden, matches all invisible elements
5DOM traversal method
In many cases, getting the parent or ancestor element of an element is a basic operation, and this is where JQuery's DOM traversal method comes in handy. With these methods, we can walk freely in the DOM tree.
The .next() method takes the closest next sibling element. In the following example, the next sibling element of the <td> element containing hery in the text is obtained.
$("td:contains(‘henry‘)").next().addClass(‘tdd‘);
<tr><td>henry</td><td>Tragedy</td><td>tyrt</td><td>fff</td></tr>
The .prev([expr]) method takes a collection of elements containing the previous sibling element immediately adjacent to each element in the set of matched elements. You can filter with an optional expression. Only the immediate sibling elements will be matched, not all of the previous sibling elements. Expr is a string type.
The .nextAll([expr]) method finds all the sibling elements after the current element.
The .prevAll([expr]) method finds all the sibling elements before the current element
.siblings(), which gets all the sibling elements after the element. In the following example, all the sibling elements after the <td> element containing hery are obtained. Of course, these sibling elements and the <td> element containing hery are valid in the same <tr>..</tr>, and are invalid for the <td> element in the following <tr>.
$("td:
Contains(‘henry‘)”).siblings().addClass(‘tdd‘);
.parent(), which gets the parent element of the element.
$("td:contains(‘henry‘)").parent().addClass(‘tdd‘);
Gets the parent element of the cell containing henry, and then matches all elements whose index value is greater than 1 in the parent element.
$("td:contains(‘henry‘)").parent().find(‘td:gt(1)‘).addClass(‘tdd‘);
.html(), get the html content of the first matching element.
.html("val"), which sets the html content of each matching element. This function cannot be used with xml documents. Such as:
$("div").html("<p>Hello Again</p>"); // Added a paragraph to the div element.
The .text() method, which means getting the contents of all matching elements, and the result returned is the text of the combined text content of all matching elements. This method works for both html and xml documents. But this method can't be used for form elements to get the value of a form element.
The .text("val") method sets the text content of all matching elements. Such as $ ("p").text ("new text."); / / change the text content of the paragraph.
$("#province option:selected").text()-----Get the content between the selected <option>....</option> in the select element. Instead of the value attribute value of <option>.
$("#province option:selected").val()---Get the value of the value of the <option> selected in the select element.
The difference between .find(expr) and .filter(expr)
.find(expr), which searches for all elements that match the specified expression from the subset. The expr expression is the same as the parameter in $().
For example: Start with all paragraphs and search for the span element below.
$("p").find("span")
If the span element has an id, it can also be $("p").find("#id")
.filter(expr), which filters out the elements in the collection that match the specified expression.
$("p").filter(".selected"), which will filter the <p> element using class="selected" in all paragraphs.
If we use the find() method:
Var $find = $("div").find(".rain");
Alert( $find.html() ) ;
Will output: Test 1
If you use the filter() method:
Var $filter = $("div").filter(".rain");
Alert( $filter.html() );
Will output: <p>Test 2</p>
The difference between them has been seen.
Find() looks for an element of class class rain inside the div element.
Filter() is the element that filters the class of the div to be rain.
One is a subset of its operations, and the other is a filter on its own collection.
jQuery determines the browser type
jQuery.browser.safari, determine if the browser is safari
jQuery.browser.opera, to determine if the browser is opera
jQuery.browser.msie, determine if the browser is IE
jQuery.browser.mozilla, to determine if the browser is mozilla
jQuery.inArray(value,array)
Determines the position of the first argument in the array, counting from 0 (returns -1 if not found).
The first parameter can be of any type.
The second parameter is the Array type.
****************************
Conversion of jQuery object and dom object
Only jquery objects can use the methods defined by jquery. Note that there is a difference between a dom object and a jquery object. When calling a method, pay attention to whether the operation is a dom object or a jquery object.
Ordinary dom objects can generally be converted to jquery objects by $().
Such as: $(document.getElementById("msg")) or var v=document.getElementById("msg");var $v=$(v)
Then for the jquery object, you can use the jquery method.
$() can contain a dom object or a query object, and the result of the conversion is a jquery object.
Convert jquery object to dom object
Since the jquery object itself is a collection. So if the jquery object is to be converted to a dom object, you must take one of them, which can be retrieved through the index or provided by jQuery itself. The corresponding getter object is obtained by the .get(index) method.
Such as: $("#msg")[0],$("div").eq(1)[0],$("div").get()[1],$("td")[5 ]
These are dom objects, you can use the methods in dom, but you can no longer use the Jquery method.
The following are all written correctly:
$("#msg").html();
$("#msg")[0].innerHTML;
$("#msg").eq(0)[0].innerHTML;
$("#msg").get(0).innerHTML;
The .eq(index) method returns the jquery object.
The .get() method gets all the matching sets of Dom elements. The returned is an array of elements, which are DOM objects instead of JQuery objects.
The .get(index) method takes one of the matching elements, and the index represents the first matching element (starting at 0). The returned object is also a Dom object.
***********************************
Description and application of jquery1.3 common selector
Basic
1. $("#id") --- the id number of the object;
2. $("div") --- Matches all elements according to the given element name;
3. $(".class") --- Matches elements according to the given CSS class;
4. $("*") --- matches all elements;
5. $("div,span,div.class") -- Combines the elements to which each selector is matched and returns them together.
Level
1. $("form input") -- matches all descendant elements under the given ancestor element;
2. $("form > input") --- Matches all child elements under the given parent element (not the same as above);
3. $("prov + next") ----- matches all next elements immediately after the prev element;
4. $("prov ~ next") --- matches all next elements after the prev element
simple
1. $("#id:first") -- matches the first element found
2. $("#id:last") -- matches the last element found
3. $("input:not(:checked)") -- removes all elements that match a given selector
4. $("tr:even") --- Matches all elements with an even index value, counting from 0
5. $("tr:odd") -- matches all elements whose index value is odd, counting from 0
6. $("tr:eq(1)") -- an element that matches a given index value (second line)
7. $("tr:gt(1)") -- matches all elements that are greater than the given index value (all rows after the second row)
8. $("tr:lt(1)") ---- matches all elements that are less than the given index value (as opposed to the above)
9. $(":header") - matches title elements like h1, h2, h3
10. $("id:animated") ---- matches all the elements that are performing the animation
content
1. $("div:contains(‘John‘)") ---- matches elements containing the given text
2. $("td:empty") - matches all empty elements that do not contain child elements or text
3. $("div:has(p)") -- matches the element containing the element matched by the selector (div with p)
4. $("td:parent") - matches elements with child elements or text
Visibility
1. $("tr:hidden") -- matches all invisible elements, or elements of type hidden
2. $("tr:visible") -- matches all visible elements
Attributes
1. $("div[id]")--matching elements containing the given attribute using [] (all divs containing id)
2. $("input[name=‘value‘]")--match the input attribute of the given attribute to a specific value
3. $("input[name!=‘value‘]")--- matches all input tag elements that have the specified attribute but whose attribute is not equal to a specific value.
4. $("input[name^=‘value‘]")----match the given attribute with an input tag element starting with some value
5. $("input[name$=‘value‘]")----match the input attribute of the given attribute with some values
6. $("input[name*=‘value‘]")---matching a given attribute is an input tag element containing some value
7. $("input[id][name$=‘value‘]")--[selector1][selector2][selector3]Composite property selector, which needs to be used when multiple conditions are met at the same time
Child element
8. $("a[name=‘value‘]")-- matches a given attribute with a specific value of the a-label element
1. $("ul li:nth-child(2)")-----match the Nth or parity element under its parent element
2. $("ul li:first-child")------- matches the first child element
3. $("ul li:last-child")-----match the last child element
4. $("ul li:only-child")---If an element is the only child element in the parent element it will be matched
5. $("ul:nth-child(index/even/odd)----match the Nth child element or parity element under its parent element. For example:
:nth-child(even),:nth-child(odd),:nth-child(2)
6. Parent>child----match all child elements under the given parent element. The values of parent and child are any valid Selector selectors. For example: Match all child input elements in the form:
$("form > input")
7. Prev + next----- matches all next elements in the parent element of prev and after the prev element. The values of prev and next are also any valid Selector selectors. Such as:
$("label + input") means that all input elements are matched in the parent element of the label and after the label element.
8. Prev ~ siblings---match the siblings element in the prev sibling element. For example: $("form ~ input") means an input element that matches the same level as the form element.
Form
1. $(":input")---matches all form elements.
2. $(":text")--matches all single-line text boxes
3. $(":password")--match all password boxes
4. $(":radio")--match all radio buttons
5. $(":checkbox")--match all checkboxes
6. $(":submit")--match all submit buttons
7. $(":image")---match all image fields
8. $(":reset")--match all reset buttons
9. $(":button")--match all buttons
10. $(":file")--match all file fields
11. $("tr:hidden")--match all invisible elements, or elements of type hidden
For example: $(‘#buton1:button‘) means a button that matches id="button1" and type=button.
Form object properties
1. $("input:enabled")--match all available elements
2. $("input:disabled")--match all unavailable elements
3. $(
"input:checked")--match all selected selected elements (checkboxes, radio buttons, etc., excluding options in select)
4. $("select option:selected")--match all selected option elements (colon: no spaces before)
$(":focus")--Get the current focus element.
**************
Input:hidden is a form element that finds invisible input elements, including textbox, radio, checkbox, button, etc. and type="hidden". Input[type=hidden] just looks for form elements of type="hidden".
Is("input[type=hidden]"), to determine whether it is an input hidden element.
*****************
Difference IE or Firefox
navigator.appName
navigator.appName is used to distinguish between different browsers, for IE output as Micrsoft Internet Explorer
For Firefox output: Netscape
****************
Dynamically add css or js files to the page header:
$("head").append("<link rel=‘stylesheet‘ type=‘text/css‘ href=‘js/binSelect/binSelect.css‘></link>”);
****************
Jquery and DWR, the two frameworks together will conflict, the solution is very simple. Add a namespace to jquery, such as:
Var $j = jQuery.noConflict(); In the future jquery, the $ is replaced with $j, so it won't conflict with $ in dwr.
If the jQuery class library conflicts with other class libraries, you can use the jQuery.noConflict() function to hand over control of the variable $ to other javaScipt libraries, then use $ to represent other javascript libraries.
})(jQuery);
The above defines a jQuery function, the formal parameter is $, after the function definition is completed, the jQuery argument is passed in. The execution is called immediately. The advantage of this is that we can also use the $ alias when writing the jQuery plugin without causing conflicts with the prototype.
*************
jQuery(function(){
});
The function is the same as the following
jQuery(document).ready(function(){
});
********************
jQuery's val("value1") method allows the select element to select an option element with a value of value1. This is fine in both IE7 and Firefox. Only IE6 will report an error. The solution is to provide a delay through setTimeout. This sentence is ok. Such as:
setTimeout(function(){$("#select1").val(setAreaValue[2]);},1);
******************
If a browser does not execute jQuery's asynchronous request and uses the previously cached data, you can add a random number to the path of the asynchronous request. This will not execute jQuery asynchronous requests using the cached data.
******************
jQuery.noConflict();
This method releases jQuery's control over the $ variable.
jQuery does not conflict with $objects of other libraries. After running this function, you can only access jQuery objects using jQuery variables.
Create a new alias to use the jQuery object in the next library.
Var j = jQuery.noConflict();
// jQuery-based code
j("div p").hide();
// based on the $() code of other libraries
$("content").style.display = ‘none‘;
***************************
In general, the order in which a page responds to loading is: domain name resolution - loading html - loading js and css - loading images and other information.
Then Dom Ready should be able to operate Dom between "load js and css" and "loading images and other information".
Dom Ready can directly operate on dom after the dom is loaded. For example, if an <img> tag is completed, you can set the width and height of the image or style without waiting for the image to be loaded.
Dom Load can directly operate on the dom after the entire document document (including other information such as loading images) is loaded. For example, a picture can be set to the width or height of the image after the icon is loaded.
Document.ready() is similar to the traditional method <body onload="load()"> except that the onload() method does not occur until the page is loaded, including DOM elements and other page elements (such as images). Load, therefore, using the document.ready() method is faster than the onload() method.
So $(document).ready(function(){...}); is executed before window.onload.
************************
Is(expr|obj|ele|fn) return value: Boolean
Detects a set of matching elements based on a selector, DOM element, or jQuery object, and returns true if at least one of the elements conforms to the given expression.
Returns 'false' if no elements match or the expression is invalid.
Expr string A string value containing a selector expression that matches the current set of elements.
jQuery object An existing jQuery object to match the current element.
Element Expression A DOM element used to match elements.
Function(index) Function A function used as a collection of test elements. It accepts a parameter index, which is the index of the element in the jQuery collection. In the function, this refers to the current DOM element.
Such as:
$("input[type=‘checkbox‘]").parent().is("form")
Var temp= $("#test").is(":hidden");//Hide it or not
Var temp1= $("#test").is(":visible");// is visible
*****************
Find all p elements, and they must all be child elements of the div element.
$("div > p");
jQuery([selector,[context]])
The core functions of jQuery are implemented through this function. By default, if no context parameter is specified, $() will look for the DOM element in the current HTML document; if a context parameter is specified, such as a DOM element set or jQuery object, it will look in this context. After jQuery 1.3.2, the order of the elements returned is equivalent to the order in which they appear in the context. Such as:
$("#exportXls",window.top.document) means looking for an element with the id exportXls under window.top.document.
1 using jQuery
The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion;
products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the
content of the page makes you feel confusing, please write us an email, we will handle the problem
within 5 days after receiving your email.
If you find any instances of plagiarism from the community, please send an email to:
info-contact@alibabacloud.com
and provide relevant evidence. A staff member will contact you within 5 working days.