Getting started with jQuery

Source: Internet
Author: User
Anyone who wants to learn jquery can read this entry-level article. Anyone who wants to learn jquery can read this entry-level article.

1. jQuery GO
JQuery provides a powerful way to read and process the document DOM, making it easy to operate the document DOM dynamically.

$(document).ready(function() { $("a").click(function() { alert("Hello world!"); }); });

Clicking any connection in the document triggers the alert () event.
$ Is an alias for the jQuery class. Therefore, $ () constructs a new jQuery object. The function click () is a method of this jQuery object. It binds a click event to all selected tags (all a tags here ), the provided alert method is executed when the event is triggered. this encoding method is more similar to separation of structure and behavior.
2. selector and event
JQuery provides two methods to select html elements. The first method is to combine CSS with the Xpath selector to form a string to be transmitted to the jQuery Constructor (for example: $ ("p> ul a"); the second is to use several methods of the jQuery object ). These two methods can also be combined for hybrid use.

 
 
  • Food
  • Clothing
  • Electronics

Use jQuery to search for ul in the document as follows: replace js document. getElementById ('orderlist ');

$(document).ready(function() { $("#orderedlist").addClass("red"); });

$ ("#...") To find the element of the specified ID.
Add a style for its subnodes as follows:

$(document).ready(function() { $("#orderedlist > li").addClass("blue"); });

Move or move the mouse away

  • Item, as follows:

    $(document).ready(function() { $("#orderedlist li:last").hover(function() { $(this).addClass("green"); }, function() { $(this).removeClass("green"); }); });

    $ (# Orderedlist li) differs from $ ("# orderedlist> li"). The former is all matched child elements under the parent element, only the matching elements in its child elements.

    $(document).ready(function() { $("#orderedlist").find("li").each(function(i) { $(this).html( $(this).html() + " BAM! " + i ); }); });

    Find () allows you to search for conditions in the selected element, so $ ("# orderedlist). find (" li ") is like $ (" # orderedlist li. The each () method iterates all the 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.
    To reset a form after an ajax request is submitted, follow these steps:

    $(document).ready(function() { // use this to reset a single form $("#reset").click(function() { $("#form")[0].reset(); }); });

    Of course, you can reset a form.

    $(document).ready(function() { // use this to reset several forms at once $("#reset").click(function() { $("form").each(function() { this.reset(); }); }); });

    Filter Selector
    Another problem you may want to face is that you do not want certain elements to be selected. JQuery provides the filter () and not () methods to solve this problem. Filter () uses a filter expression to reduce the selected items that do not match. 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"); });

    In the above Code, the [expression] 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"); // the original file is "$ (" a [@ name] "). background ("# eee"); "in jQuery1.2 and later versions, the @ symbol should be removed });

    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, our partial match ("* =") [contains] instead of 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(':visible')) { 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', it is selected only once. Using the end () method, the first find () method will end (undone ), therefore, we can continue to find ('dt') later without writing $ ('# faq '). find ('dt ').

    In the click event, we use $ (this). next () to locate the next dd element under dt. this allows us to quickly select the answer below the clicked question.
    SlideUp (speed, [callback]) speed slow normal fast or numeric value, callback function
    You can dynamically hide all matching elements by changing the height (decreasing upwards) and trigger a callback function after hiding.
    This animation only adjusts the height of the element, so that the matching element can be hidden by sliding.
    SlideDown (speed, [callback])
    Dynamically displays all matching elements by increasing the height (down). A callback function is triggered after the display is complete.
    This animation only adjusts the height of the element, so that the matching element is displayed as a slide.
    In addition to the element of the same level, you can also select the element of the parent level. When you move the user's mouse over a link in a certain segment of the article, its parent element is highlighted in this section of the article. Try this:

    $ (Document ). ready (function () {$ (""). hover (function () {$ (this ). parents ("p "). addClass ("highlight") ;}, function () {$ (this ). parents ("p "). removeClass ("highlight") ;}}); $ (document ). the abbreviation of ready (callback): $ (function) $ (function () {// code to execute when the DOM is ready });

    In our Hello world example, we can:

    $(function() { $("a").click(function() { alert("Hello world!"); }); });

    Although these examples can be implemented without AJAX, it is shown that we will not do this. We use jQuery to generate a p container with the ID "rating ".

    $(document).ready(function() { // generate markup var ratingMarkup = ["Please rate: "]; for(var i=1; i <= 5; i++) { ratingMarkup[ratingMarkup.length] = "" + i + " "; } // add markup to container and applier click handlers to anchors $("#rating").append( ratingMarkup.join('') ).find("a").click(function(e) { e.preventDefault(); // send requests $.post("rate.php", {rating: $(this).html()}, function(xml) { // format result var result = [ "Thanks for rating, current average: ", $("average", xml).text(), ", number of votes: ", $("count", xml).text() ]; // output result $("#rating").html(result.join('')); } ); }); });

    This code generates five links and appends them to the "rating" container. When one of the links is clicked, the score indicated by this link is sent to rate as the rating parameter. php. Then, the results will be passed back from the server in XML format and added to the container to replace these links.
    An issue that often occurs when using AJAX to load content is: when loading an event handle to an HTML document, you also need to apply these events on the loaded content, you have to apply these event handles after the content is loaded. To prevent repeated code execution, you may use the following function:

    // lets use the shortcut $(function() { var addClickHandlers = function() { $("a.clickMeToLoadContent").click(function() { $("#target").load(this.href, addClickHandlers); }); }; addClickHandlers(); });

    Now, addClickHandlers is executed only once after the DOM is loaded. This is after you click a link with the clickMeToLoadContent style and the content is loaded.
    Note that the addClickHandlers function is defined as a local variable instead of a global variable (for example, function addClickHandlers (){...}), this is done to prevent conflicts with other global variables or functions.
    Another common problem is the callback parameter. You can use an additional parameter to specify the callback method. The simple method is to include this callback method in another function:

    // get some data var foobar = ...; // specify handler, it needs data as a paramter var handler = function(data) { ... }; // add click handler and pass foobar! $('a').click( function(event) { handler(foobar); } ); // if you need the context of the original handler, use apply: $('a').click( function(event) { handler.apply(this, [foobar]); } );

    Animate me (Let me be vivid): Use FX
    Some dynamic effects can be presented using show () and hide:

    $(document).ready(function() { $("a").toggle(function() { $(".stuff").hide('slow'); }, function() { $(".stuff").show('fast'); }); });

    You can work with animate () to create some effects, such as a sliding effect with a gradient:

    $(document).ready(function() { $("a").toggle(function() { $(".stuff").animate({ height: 'hide', opacity: 'hide' }, 'slow'); }, function() { $(".stuff").animate({ height: 'show', opacity: 'show' }, 'slow'); }); }); toggle(fn,fn)

    Call the function after each click.
    If a matching element is clicked, the specified first function is triggered. When the same element is clicked again, the specified second function is triggered. If more functions exist, trigger again until the last one. The subsequent clicks repeatedly call these functions.
    You can use unbind ("click") to delete it.
    Animate (params, options)
    A function used to create a custom animation.
    The key to this function is to specify the animation form and result style attribute object. Each attribute in this object represents a changeable style attribute (such as "height", "top", or "opacity ").
    Note: All specified attributes must be in the camel format. For example, margin-left must be replaced by marginLeft.
    The value of each attribute indicates the animation ends when the style attribute is reached. If it is a value, the style property will gradually change from the current value to the specified value. If a string value such as "hide", "show", or "toggle" is used, the default animation format is called for this attribute.

    $("#go1").click(function(){ $("#block1").animate( { width: "90%"}, { queue: false, duration: 5000 } ) .animate( { fontSize: '10em' } , 1000 ) .animate( { borderWidth: 5 }, 1000); }); $("#go2").click(function(){ $("#block2").animate( { width: "90%"}, 1000 ) .animate( { fontSize: '10em' } , 1000 ) .animate( { borderWidth: 5 }, 1000); });

    Use the tablesorter plug-in (Table sorting)
    This table sorting plug-in allows us to sort by column on the client, introduce jQuery and js files of this plug-in, and then tell the plug-in which table you want to have the sorting function.
    To test this example, first Add the following line of code in starterkit.html:

  • 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.