Home >Web Front-end >JS Tutorial >Understand jQuery techniques to improve your code (I personally think the jquery manual is very good)_jquery

Understand jQuery techniques to improve your code (I personally think the jquery manual is very good)_jquery

WBOY
WBOYOriginal
2016-05-16 17:56:26991browse
jquery-选择器-技巧
2. Test whether a jQuery wrapper set contains certain elements
If you want to test whether a jQuery wrapper set contains certain elements, you can first try to verify whether the first element exists:
Copy code The code is as follows:

if($(selector)[0]){... }
// Or like this
if($(selector).length){...}

Let’s look at this example:
Copy the code The code is as follows:

//Example. If your page has the following html code

  • Item X

  • Item Y
  • Item Z


... 
//This if condition will return true because we have two
// input fields matching the selector, so the code will execute
if($( '#shopping_cart_items input.in_stock')[0]){}

3. Read the latest version of jQuery from jquery.org
You can use this code to read jQuery The latest version of the code file.


You can use this method to call the latest version of the jQuery framework , of course, you can also use the following code to call the same latest version of jQuery from ajax.googleapis.com:


4. Store data
Use the data method to avoid storing data in the DOM. Some Front-end developers like to use HTML attributes to store data:
Copy code The code is as follows:

$('selector').attr('alt', 'data being stored');
//You can read the data like this later:
$('selector').attr('alt');

Using the "alt" attribute as a parameter name to store data is actually not semantic for HTML. We can use jQuery's data method to store data for an element in the page:
Copy code The code is as follows:

$('selector').data('parameter name', 'Data to be stored');
//Then get the data like this:
$('selector').data('parameter');

This data method allows you You can clearly define the data parameters yourself, which is more semantic and flexible. You can store data information in any element on the page. If you want to know more about the data() and removeData() methods, you can read the jQuery official explanation

The classic application of this method is to give the input field a default value, and then clear it when focusing:
HTML part:
Copy code The code is as follows:







JavaSript part:
Copy code The code is as follows:

$(function() {
//Take out the input field with clear class
//(Note: "clear once" is two classes clear and once)
$(' #testform input.clear').each(function(){
//Use data method to store data
$(this).data( "txt", $.trim($(this).val() ) );
}).focus(function(){
// When getting focus, determine whether the value in the field is the same as the default value. If it is the same, clear it
if ( $.trim($(this)) .val()) === $(this).data("txt") ) {
$(this).val("");
}
}).blur(function() {
// Add blur time to the field with class clear to restore the default value
// But if the class is once, ignore it
if ( $.trim($(this).val()) = == "" && !$(this).hasClass("once") ) {
//Restore saved data
$(this).val( $(this).data("txt") );
}
});
});

5. Keep the jQuery manual close at hand
Most people have a hard time remembering all the programming details, no matter how good they are Most programmers will also be careless about a certain programming language, so printing out the relevant manuals or putting them on the desktop for reference at any time can definitely improve programming efficiency.
oscarotero jquery 1.3 (Wallpaper version)
jQuery手册
6. Record jQuery in FireBug console
FireBug is my favorite one. One of the browser extension tools, this tool allows you to quickly understand the HTML CSS JavaScript of the current page in the visual interface, and complete instant development under this tool. As a jQuery or JavaScript developer, FireFox is also supported for logging your JavaScript code.

The easiest way to write to the FireBug console is as follows:
console.log("hello world")

firebug-jquery-控制台
You can also write some parameters the way you want:

console.log(2,4,6,8,"foo",bar)
You also You can write a small extension to log jQuery objects to the console:

Copy the code The code is as follows:

jQuery.fn.log = function (msg) {
console.log("%s: %o", msg, this);
return this;
};

For this extension, you can directly use the .log() method to log the current object to the console.
Copy code The code is as follows:

$('#some_div').find('li .source > input:checkbox')
.log("sources to uncheck")
.removeAttr("checked");

7. Use ID selectors whenever possible
After using jQuery, you will find that it is quite simple to use the class attribute to select DOM elements. Despite this, it is recommended that you use class selectors as little as possible instead and use ID selectors that run faster as much as possible (using class selectors in IE browser will return a matching class packaging set after traversing the entire DOM tree). The ID selector is faster because the DOM itself has a "natural" getElementById method, but class does not. So if you use class selectors, the browser will traverse the entire DOM. If the DOM structure of your web page is complex enough, these class selectors are enough to make the page slower and slower. Let’s look at this simple HTML code:
Copy the code The code is as follows:

< ;div id="main">

Selectors in jQuery


...
...


// Using a class to call the submit button is much slower than using an absolute ID selector
var main_button = $('#main .button');
var main_button = $('#main_button');

8. Make good use of jQuery chain
jQuery chain not only allows powerful operations to be written in a concise way, but also improves development efficiency because it can apply multiple commands to the package set without having to recalculate Packaging set. So you no longer have to write like this:
Copy the code The code is as follows:

  • Description:
  • $('#shopping_cart_items input.text').css( 'border', '3px dashed yellow');
    $('#shopping_cart_items input.text').css('background-color', 'red');
    $('#shopping_cart_items input.text' ).val("text updated");

    Instead you can use jQuery chain to complete the simple operation:
    Copy code The code is as follows:

    var input_text = $('#shopping_cart_items input.text');
    input_text.css('border', '3px dashed yellow') ;
    input_text.css('background-color', 'red');
    input_text.val("text updated");

    //same with chaining:
    var input_text = $('#shopping_cart_items input.text');
    input_text
    .css('border', '3px dashed yellow')
    .css('background-color', 'red')
    .val("text updated");
    [html]
    9. Bind jQuery function to $(window).load event
    Most jQuery examples or tutorials tell us to bind our jQuery code to the $(document).ready event. Although the $(document).ready event is OK in most cases, its parsing sequence starts when the document is ready and objects such as images in a single document are being downloaded. Therefore, using the $(document).ready event may not necessarily achieve the results we expect at certain times, such as some visual effects and animations, dragging, pre-reading hidden pictures, etc... By using the $(window).load event It's safe to wait until the entire document is ready before running your desired code.
    [code]
    $(window).load(function(){
    // Put the code you want to run after the page is fully ready here
    });

    10. Use jQuery chains to limit selectors, making your code more concise and elegant
    Since JavaScript supports chain structures and line breaks, your code can be written as follows. This example first moves the element up Remove one class and add another class to the same element:
    Copy code The code is as follows:

    $('#shopping_cart_items input.in_stock')
    .removeClass('in_stock')
    .addClass('3-5_days');

    If you want to make it easier Practical, you can create a jQuery function that supports chain structure:
    Copy the code The code is as follows:

    $.fn.makeNotInStock = function() {
    return $(this).removeClass('in_stock').addClass('3-5_days');
    }
    $('#shopping_cart_items input. in_stock').makeNotInStock().log();

    11. Use callback function to synchronize effects
    If you want to ensure that an event or animation effect is called after another event is run , then you have to use the callback function. You can bind callback functions behind these animation effects: slideDown( speed, [callback] ) ie. $('#sliding').slideDown('slow', function(){… Click here to preview this example.
    Copy code The code is as follows:

    $(document).ready(function(){
    // Use jQuery’s click event to change the visual effect and enable the sliding effect
    $("div.button" ).click(function () {
    //div.button now looks like the effect of being pressed
    $(this).css({ borderStyle:"inset", cursor:"wait" });
    //#sliding will now fade out and turn on the fade-in effect after completing the action
    //slideup once it completes
    $('#sliding').slideDown('slow', function(){
    $('#sliding').slideUp('slow', function(){
    //After the fade effect is completed, the CSS properties of the button will be changed
    $('div.button').css ({ borderStyle:"outset", cursor:"auto" });
    });
    });
    });
    });

    12 .Learn to use custom selectors
    jQuery allows us to define custom selectors based on css selectors to make our code more concise:
    Copy code The code is as follows:

    $.expr[':'].mycustomselector= function(element, index, meta, stack){
    // element- DOM element
    // index - the currently traversed index in the stack value
    // meta - the data element about your selector
    // stack - the stack used to iterate over all elements

    // returns true if the current element is included
    // no Return false if the current element is included
    };

    // Application of custom selector:
    $('.someClasses:test').doSomething();

    Let's take a look at a small example below, where we use a custom selector to lock the set of elements containing the "rel" attribute:
    Copy code The code is as follows:

    $.expr[':'].withRel = function(element){
    var $this = $(element);
    / /Only return elements whose rel attribute is not empty
    return ($this.attr('rel') != '');
    };

    $(document).ready(function( ){
    //The use of custom selectors is very simple. Like other selectors, it returns an element packaging set
    //You can use the formatting method for it, such as modifying its css style as follows
    $('a:withRel').css('background-color', 'green');
    });

    13. Preload images
    Usually using JavaScript to preload images is a good way:
    Copy code The code is as follows:

    //Define the function to preload the image list (with parameters)
    jQuery.preloadImages = function(){
    //Traverse the images
    for(var i = 0; ijQuery("").attr("src", arguments[i]);

    }
    }
    // You can use the preload function like this
    $.preloadImages("images/logo.png", "images/logo-face.png", "images/mission.png");

    14. Test your code well
    jQuery has a unit testing framework called QUnit. Writing tests is easy and allows you to modify your code with confidence and ensure it still works as expected. Here's how it works:
    Copy code The code is as follows:

    //Split the test into several Module.
    module("Module B");

    test("some other test", function() {
    //Specify how many judgment statements need to be added to the test.
    expect (2);

    equals( true, false, "failing test" );
    equals( true, true, "passing test" );
    });
    Statement:
    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
    Previous article:ASP.NET jQuery Example 18 Validating DropDownList_jquery by using jQuery validation plug-inNext article:ASP.NET jQuery Example 18 Validating DropDownList_jquery by using jQuery validation plug-in

    Related articles

    See more