Home > php教程 > PHP开发 > jQuery starting tutorial: using selectors and events

jQuery starting tutorial: using selectors and events

黄舟
Release: 2016-12-14 16:40:00
Original
1399 people have browsed it

jQuery starting tutorial - using selectors and events
jQuery provides two ways to select HTML elements:

The first is to use CSS and Xpath selectors to combine to form a string to be sent to jQuery's constructor ( Such as: $("div > ul a"));

The second method is to use several methods of jQuery objects. These two methods can also be used in combination.



To test these selectors, let's try to select and modify the first ordered list in our starterkit.html.

First, we need to select the list itself, which has an ID called "orderedlist" The usual JavaScript writing is the document.GetelementByid ("OrderEdlist"). In jQuery, we do this: $ (docume). READY () ");
}); Here a CSS style red in the starterkit is attached to the orderedlist (Translator Keel’s note: refer to core.css in the css directory in the test package, which defines the red style). So, after you refresh the starterkit.html, you will see that the background color of the first ordered list changes to red, while the second ordered list remains unchanged.
Now, let’s add some New styles to the child nodes of the list.$(document).ready(function() {
            $("#orderedlist > li").addClass("blue");
}); In this way, all li in the orderedlist All have the style "blue" appended.

Now let’s do something a little more complicated, switching styles when the mouse is placed on and away from the li object, but it only takes effect on the last element of the list. $(document).ready(function() {
                                                                              $(document). $(this).removeClass("green");
});
}); There are also tons of similar CSS and XPath examples. More examples and lists can be found here. (Translator Keel’s note: Read this article to get started. Cultivation depends on the individual. If you want to know more after getting started, you must read the links in this paragraph sooner or later!)

Every onXXX event is valid, such as onclick, onchange, onsubmit, etc. all have jQuery equivalent representation methods (Translator Keel's note: jQuery doesn't like onXXX, so they were changed to XXX and on was removed). Some other events, such as ready and hover, also provide corresponding methods.

You can find the full event list in Visual jQuery, under the Events column.

You can already do a lot of things with these selectors and events, but here is something even better! $(document).ready(function() {
                                                                                                                                               + " BAM! " + i );
         });
});


find() allows you to perform a conditional search in the selected element, so $("#orderedlist).find("li") is Like $("#orderedlist li").

each() iterates over all li, and can do more processing on this basis. Most methods, such as addClass(), can use their own. each().

In this example, html() is used to get the html text of each li, append some text, and set it as the html text of li. (Translator Keel's note: You can see from this example. The .html() method is to get the html code of the object, and .html('xxx') is to set 'xxx' as the html code of the object)



Another often encountered task is to call some methods on DOM elements that are not covered by jQuery. Imagine a reset after you successfully submit it using AJAX: $(document).ready(function() {
/ / use this to reset a single form
                                                                                                     Keel's note: The author here also writes the id of the form as form. The source file has

. This is a very bad way of writing. You can change the ID to form1 or testForm, and then use $ ("#form1") or $("#testForm") to represent it, and then test it. )

This code selects all 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() {
                                                                                                                                                                                         
                                                                   You have to write these codes yourself in custom .js and test the effect on starterkit.html to get a feel for it! Observe the html code of starterkit.html if necessary)

In this way, after clicking the Reset link, you will select all the form elements in the document and modify them reset() is executed once.

Another problem you may have to face is not wanting certain elements to be selected. jQuery provides filter() and not() methods to solve this problem. filter() uses a filter expression to reduce the selected items that do not match the filter expression, and not() is used to cancel all selected items that match the filter expression. Consider an unordered list, and you want to select all elements that do not have ul subelements. li element. $(document).ready(function() {
               $("li").not("[ul]").css("border", "1px solid black");
});This code selects all li elements, and then remove the li elements without ul sub-elements. After refreshing the browser, all li elements have a border, except for the li element of the ul sub-element.

(Translator Keel’s note: Please pay attention to the extremely convenient css() method, and remind you again to actually test and observe the effect. For example, what about changing a CSS style? What about adding another CSS style? Like this: $(" li").not("[ul]").css("border", "1px solid black").css("color","red");)

The [expression] syntax in the above code is from Coming from XPath, it can be used as a filter on elements and attributes. For example, you may want to select all links with a name attribute: a[@name]").background("#eee");
});This code adds a background color to all links with the name attribute. (Translator Keel's note: This color is too subtle, it is recommended to write it as $("a[@name]").background("red");)

The more common situation is to select the link by name, you may need Choose a link with a characteristic href attribute. The understanding of href may be inconsistent in different browsers, so we use partial matching ("*=") instead of full matching ("="): $(document ).ready(function() {
                                                                                   );
});Up to now, selectors have been used to select child elements or filter elements. Another situation is to select the previous or next element, such as a FAQ page. The answer will be hidden first. When the question is clicked, the answer will be 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')) {
                                                                                                                                  });Here we use some chain expressions to reduce the amount of code and make it look more intuitive and easier to understand. Like '#faq' is only selected once, using the end() method, the first find() method will end (undone), so we can continue to find('dt') later without writing $( '#faq').find('dt').

In the click event, we use $(this).next() to find a dd element immediately below dt, which allows us to quickly select the answer under the clicked question.

(Translator Keel's note: This example is really cool. The answers in the FAQ can be shrunk! From the idea of ​​using next() to realizing these effects, there are many places that we need to digest. Pay attention to if (answer.is(': visible')) usage, pay attention to answer.slideUp(); if you don’t understand anything, please check the two must-read API documents I mentioned at the beginning)

In addition to selecting elements of the same level, you can also select the parent level element. Maybe you want to highlight the parent element of a link in a certain paragraph of the article when the user moves the mouse. Try this: $(document).ready(function() {
           ("a").hover(function() {
                                                                                                                                                                                        ("a"). ).removeClass("highlight");
     });
}); As you can see from the test results, when you move a link to a certain section of the article, the section where it is located will all use the highlight style, and it will return to its original state after it is removed.

(Translator Keel’s note: highlight is the style defined in core.css. You can also change it. Note that there is a second function() here. This is the characteristic of the hover method. Please check hover in the API document. It is also mentioned above. Example)
Let’s take a look at this step before we continue: jQuery will make the code shorter and easier to understand and maintain. Here is the abbreviation of $(document).ready(callback): $(function( ; alert("Hello world!");
      });
}); Now that we have these basic knowledge in hand, we can further explore other aspects, starting with AJAX!

For more related articles, please pay attention to the PHP Chinese website (m.sbmmt.com)!



Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template