Getting started with jquery using selector and events (3)

Source: Internet
Author: User

Getting started with jquery using selector and events
Jquery provides two methods to select HTML elements:

    • The first type is to combine CSS with the XPath selector to form a string to be transmitted to the jquery Constructor (for example, $ ("div> ul "));
    • The second method is to use several methods of the jquery object ). These two methods can also be combined for hybrid use.

To test the selection, we try to select and modify the first ordered in starterkit.html.
List.

In the beginning, we need to select the List itself. This list has an ID called "orderedlist", and the common JavaScript syntax is document. getelementbyid ("orderedlist "). in jquery, we do this:

$ (Document). Ready (function (){

$ ("# Orderedlist"). addclass ("red ");
});

Append a CSS style red in starterkit to orderedlist (translator keel Note: Refer to core.css In the CSS directory of the test package, which defines the red style ). After you refresh starterkit.html, you will see the first ordered list (ordered
List) the background color turns red, but the second ordered list does not change.
Now, let's add some new styles to the list subnodes.

$ (Document). Ready (function (){

$ ("# Orderedlist>
Li "). addclass (" blue ");
});

In this way, the style "blue" is appended to Li in all orderedlist ".

Now let's make it a little more complicated. When you move the mouse over the Li object and move it away, style switching will take effect only on the last element of the list.

$ (Document). Ready (function (){

$ ("# Orderedlist Li: Last"). Hover (function (){

$ (This). addclass ("green ");
}, Function (){

$ (This). removeclass ("green ");

});
});

There are also a lot of examples similar to CSS and XPath, more examples and lists can be found here. (Translator keel Note: This article is for beginners. If you want to learn more after getting started, several links in this article will be required sooner or later !)

Every onxxx event is valid, such as onclick, onchange, and onsubmit. There are jquery equivalent representation (translator keel Note: jquery does not like onxxx, so it is changed to XXX, remove on ). Other events, such as ready and hover, also provide corresponding methods.

You can
Find the list of all events in jquery, under the events column.

You can do a lot with these selectors and events, but here is a better thing!

$ (Document). Ready (function (){

$ ("# Orderedlist"). Find ("Li"). Each (function (I ){

Certificate (this).html (certificate (this).html () + "Bam! "+ I );

});
});
    • Find () allows you to search for conditions in the selected element, so $ ("# orderedlist). Find (" Li ") is like
      $ ("# Orderedlist li ").
    • Each () iterates all Li resources and can perform more processing on this basis. Most methods, such as addclass (), can use their own each ().
    • In this example, HTML () is used to obtain the HTML text of each Li,
      Append some text and set it to the HTML text of Li. (Translator keel Note: from this example, we can see that the .html () method is to get the HTML of the object.CodeAnd. html ('xxx') is the HTML code that sets 'xxx' as the object)

Another common task is to call some methods on the DOM element that is not covered by jquery. Imagine a reset after you successfully submit it using Ajax:

$ (Document). Ready (function (){
//
Use this to reset a single form
$ ("# RESET"). Click (function (){
 
$ ("# Form") [0]. Reset ();

});
});

(Translator keel Note: here the author also writes the Form ID into form, the source file has <form
Id = "form">. This is a very bad method. You can change this ID to form1 or testform, and then use $ ("# form1") or $ ("# testform ") to represent it, and then test .)

This code Selects all the elements with the ID "form" and calls a reset () on the first one (). If you have more than one form, you can do this:

$ (Document). Ready (function (){
//
Use this to reset several forms at once
$ ("# RESET"). Click (function ()
{
$ ("Form"). Each (function (){

This. Reset ();
});

});
});

(Translator keel Note: Please be sure to write the code in custom.js and test the effect on starterkit.html! Observe the HTML code of starterkit.html when necessary)

In this way, after you click the reset link, you select all form elements in the document and execute a reset () for them ().

Another problem you may want to face is that you do not want certain elements to be selected. Jquery
The filter () and not () methods are provided to solve this problem. Filter () is used as a filter expression to reduce non-conforming selected items,
Not () is used to cancel all selected items that match the filter expression. Consider an unordered list. You want to select all Li elements without ul sub-elements.

$ (Document). Ready (function (){

$ ("Li"). Not ("[ul]" ).css ("border", "1px solid
Black ");
});

This code Selects all the Li elements and removes the Li elements without ul sub-elements. After refreshing the browser, all the Li elements have a border, except the Li element of the UL sub-element.

(Translator keel Note: Pay attention to the very convenient CSS () method, and remind you again to test the observed effect, for example, change the CSS style? What about a CSS style? Like this: $ ("Li"). Not ("[ul]" ).css ("border ",
"1px solid black" ).css ("color", "Red ");)

[Expression] in the above Code
The syntax comes from XPath and can be used as a filter on the child elements and attributes (elements and attributes). For example, you may want to select all links with the name attribute:

$ (Document). Ready (function (){

$ ("A [@ name]"). Background ("# Eee ");
});

This Code adds a background color to all links with the name attribute. (Translator keel Note: The color is too obscure. We recommend that you write $ ("A [@ name]"). Background ("red ");)

A more common scenario is to select links by name. You may need to select a link with the href attribute, which may have different href understandings in different browsers, therefore, we partially match ("* =") to replace the full match ("= "):

$ (Document). Ready (function (){

$ ("A [@ href * =/content/gallery]"). Click (function (){
// Do
Something with all links that point somewhere to/content/Gallery

});
});

Up to now, selectors are used to select child elements or filter elements. Another scenario is to select the previous or next element. For example, on a faq page, the answer is hidden first. When a question is clicked, the answer is displayed. The jquery code is as follows:

$ (Document). Ready (function (){

$ ('# FAQ'). Find ('dd'). Hide (). End (). Find ('dt'). Click (function (){

VaR answer = $ (this). Next ();
If (answer. Is (': visable ')){

Answer. slideup ();
} Else {

Answer. slidedown ();
}
 
});
});

Here we use some chained expressions to reduce the amount of code, and it looks more intuitive and easier to understand. Like '# FAQ'
The end () method is used only once. The first find () method ends (undone), so we can continue to find ('dt ') later '), instead of writing $ ('# FAQ '). find ('dt ').

In the click event, we use
$ (This). Next ()
To find the next dd element under DT, which allows us to quickly select the answer to the question being clicked.

(Translator keel Note: This example is really cool. The answers in the FAQ can be reduced! There are many things that need to be digested from using next () to achieving these effects.
If
(Answer. Is (': visable') usage. Pay attention to answer. slideup (). If you don't understand it, check the two API documents that I mentioned at the beginning)

In addition to the element of the same level, you can also select the element of the parent level. Maybe you want to move the mouse over the userArticleWhen a link of a segment is displayed, its parent element is highlighted in this section of the article. Try this:

$ (Document). Ready (function (){

$ ("A"). Hover (function (){

$ (This). Parents ("p"). addclass ("highlight ");
}, Function (){

$ (This). Parents ("p"). removeclass ("highlight ");

});
});

The test results show that when you move the link to a certain section of the article, the section where it is located uses the highlight style. After the link is removed, it is restored to its original state.

(Translator keel Note: highlightis the style defined in core.css. You can also change it. Note that the second function () is a feature of the hover method. Please refer to hover in the API documentation, the example above is also described)

Before proceeding, let's take a look at this step:
Jquery makes the code shorter and easier to understand and maintain. The following is the abbreviation of $ (document). Ready (callback:

$ (Function (){
// Code
Execute when the Dom is ready
});

In our Hello world example, we can:

$ (Function (){

$ ("A"). Click (function (){
Alert ("Hello world! ");

});
});

Now that we have the basic knowledge, we can further explore other things, starting with Ajax!

Links to this chapter:

    • jquery API
      documentation
    • visual jquery-A
      categorized browsable API documentation
    • jquery
      expressions: CSS
    • jquery
      expressions: XPath
    • jquery expressions: Custom
    • jquery special
      events
    • jquery Dom
      traversing
Related Article

Contact Us

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.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.