In the process of using JQ, there are some tips:
1.is() method
The set of matching elements is detected based on the selector, element, or jQuery object. If at least one of these elements matches a given parameter, it returns true. Some small applications are as follows:
<ul> <li>list <strong>item 1</strong></li> <li><span>list item 2</span></li> <li>list item 3</li> </ul>
$("ul").click(function(event) { var $target = $(event.target); if ( $target.is("li") ) { $target.css("background-color", "red"); } });
In this way, you can limit the number of clicks that are written to you only after the list item li itself is clicked.
It can also make the following judgments:
// Is it one? div elem.is('div') && console.log("it's a div"); // Is it included?(There can also be other class names.)bigbox Elements of class names? elem.is('.bigbox') && console.log("it has the bigbox class!"); // Is it hidden?? elem.is(':not(:visible)') && console.log("it is hidden!");
It is important to note that the & & operator can be used to make a judgment. When the current condition is satisfied, the latter condition will be executed, but the latter condition can not be an expression, but can only be console.log() or + + i.
There are also some useful uses as follows:
elem.animate({'width':200},1000); // Are you animating? elem.is(':animated') && console.log("it is animated!");
2. Extended methods in jquery
FN refers to the namespace of jquery, plus the methods and attributes on fn, which will be valid for each jQuery instance.
If extending $. fn.abc(), or $. fn.abc(), extends an abc method to jquery, then every jQuery instance can refer to this method later.
Then you can do this: $("#div").abc();
jQuery.extend(object); add new methods to the class to extend the jQuery class itself.
jQuery.fn.extend(object); add methods to jQuery objects.
jQuery.extend(object); Adding class methods to jQuery classes can be understood as adding static methods. Such as:
$.extend({ add:function(a,b){returna+b;} });
add a "static method" for jQuery, and then you can use this method where jQuery is introduced.
$.add(3,4);
//return 7
jQuery.fn.exists = function(){ return this.length > 0; } console.log($('#elem').exists() ? "exists!" : "doesn't exist!");
3. The jQuery method $() actually has two parameters
$('li','#firstList').each(function(){ console.log($(this).html()); });
Here, the second parameter is used to restrict the search result given by the first parameter.
$('<div>',{ "class": "bigBlue", "css": { "background-color":"purple" }, "width" : 20, "height": 20, "animate" : { // Can set div Animation effects "width": 200, "height":50 } }).appendTo('#result');
Here, the second parameter is used to set the elements created.
4. The end() method in jQuery can make chain grammar more efficient and fast.
<ul id="meals"> <li> <ul class="breakfast"> <li class="eggs">No</li> <li class="toast">No</li> <li class="juice">No</li> </ul> </li> </ul>
breakfast.find('.eggs').text('Yes').end() // back to breakfast .find('.toast').text('Yes').end().find('.juice').toggleClass('juice coffee').text('Yes');
Here, end() returns to the previous level of the lookup element.
5.contextmenu event right-click
Perhaps if you want web applications to feel more native, you can prevent contextmenu default events.
$(function(){ $(document).on("contextmenu",function(e){ e.preventDefault(); }); });
Of course, when you apply this event, you can also customize the right-click action menu, similar to
6. Sometimes we don't want a part of the page to be selected, such as copying and pasting. We can do this:
$('p.descr').attr('unselectable', 'on').css('user-select', 'none').on('selectstart', false);
In this way, content can no longer be selected.
7. Minimum DOM operations
Operating DOM with js is a waste of resources. The following methods are generally our usual practice:
var elem = $('#elem'); for(var i = 0; i < 100; i++){ elem.append('<li>element '+i+'</li>'); }
In this way, adding repetitive elements is undoubtedly a huge waste of resources, and through the following methods, you can reduce a large number of DOM operations.
var elem = $('#elem'),
arr = []; for(var i = 0; i < 100; i++){ arr.push('<li>element '+i+'</li>'); } elem.append(arr.join(''));
8. More convenient decomposition of URL s
We can usually use regular expressions to decompose URLs, but this is not a good way. We can use a tag to decompose URLs.
var url = 'http://tutorialzine.com/books/jquery-trickshots?trick=12&&abc=123#comments'; var a = $('<a>',{ href: url }); console.log(url); console.log('Host name: ' + a.prop('hostname')); //Host name: tutorialzine.com console.log('Path: ' + a.prop('pathname')); //Path: /books/jquery-trickshots console.log('Query: ' + a.prop('search')); //Query: ?trick=12&&abc=123 console.log('Protocol: ' + a.prop('protocol')); //Protocol: http: console.log('Hash: ' + a.prop('hash')); //Hash: #comments
In this way, we can quickly decompose the URL.
9. Sometimes caching selector s can optimize your js
There are three situations below. The first one is the common practice of some people. This writing is laborious and unpleasant. The latter two schemes are the optimization of the first one, which can be chosen by two choices.
The first is:
$('#pancakes li').eq(0).remove(); $('#pancakes li').eq(1).remove(); $('#pancakes li').eq(2).remove();
The second and the third can be chosen as one of two.
//Second kinds
var pancakes = $('#pancakes li'); pancakes.eq(0).remove(); pancakes.eq(1).remove(); pancakes.eq(2).remove();
//Third kinds pancakes.eq(0).remove().end().eq(1).remove().end().eq(2).remove().end();
10.on() method
The on() method adds one or more event handlers to the selected elements and child elements.
Since version 1.7 of jQuery, the on() method has been a new alternative to the bind(), live() and delegate() methods. This method brings a lot of convenience to API. It is recommended to use this method, which simplifies the jQuery code base.
Note: Event handlers added using the on() method apply to current and future elements (such as new elements created by scripts).
Tip: If you need to remove event handlers, please use ____________ off() Method.
Tip: If you need to add an event that runs only once and then remove it, please use ___________ one Method.
$(selector).on(event,childSelector,data,function,map)
11. Simulate trigger events
We can trigger a click event through trigger simulation
var press = $('#press'); press.on('click',function(e, how){ how = how || ''; alert('The buton was clicked ' + how + '!'); }); press.trigger('click'); press.trigger('click',['fast']);
At the same time, we can also use the on() method to create the name of the event we like, and then trigger it by triggering. Examples are as follows:
<button id="button1">Jump</button> <button id="button2">Punch</button> <button id="button3">Click</button> <button id="clear" style="float: right;">Clear</button> <div id="eventDiv"></div>
var button1 = $('#button1'), button2 = $('#button2'), button3 = $('#button3'), clear = $('#clear'), div = $('#eventDiv'); div.on({ jump : function(){ alert('Jumped!'); }, punch : function(e,data){ alert('Punched '+data+'!'); }, click : function(){ alert('Simulated click!'); } }); button1.click(function(){ div.trigger('jump'); }); button2.click(function(){ // Pass data along with the event div.trigger('punch',['hard']); }); button3.click(function(){ div.trigger('click'); }); clear.click(function(){ //some clear code });
12. Touch events
// Define some variables var ball = $('<div id="ball"></div>').appendTo('body'), startPosition = {}, elementPosition = {}; // Listen for mouse and touch events ball.on('mousedown touchstart',function(e){ e.preventDefault(); // Normalizing the touch event object e = (e.originalEvent.touches) ? e.originalEvent.touches[0] : e; // Recording current positions startPosition = {x: e.pageX, y: e.pageY}; elementPosition = {x: ball.offset().left, y: ball.offset().top}; // These event listeners will be removed later ball.on('mousemove.rem touchmove.rem',function(e){ e = (e.originalEvent.touches) ? e.originalEvent.touches[0] : e; ball.css({ top:elementPosition.y + (e.pageY - startPosition.y), left: elementPosition.x + (e.pageX - startPosition.x), }); }); }); ball.on('mouseup touchend',function(){ // Removing the heavy *move listeners ball.off('.rem'); });
13. Prevent default events faster
Usually, we use event.preventDefalut() to block default events, but jquery provides a simpler way to do this:
<a href="http://google.com/" id="goToGoogle">Go To Google</a>
$('#goToGoogle').click(false);
14. Link multiple event handlers using event.result.
It is not common to bind multiple event handlers to an element, but event.result can be used to connect multiple event handlers. Look at the following example.
var press = $('#press'); press.on('click',function(){ return 'Hip'; }); press.on('click',function(e){ console.log(e.result + ' Hop!'); }) //console output: HipHop!
15. Running multiple Ajax requests in parallel
When we need to send multiple Ajax requests, instead of waiting for one to finish before sending the next, we can send them in parallel to speed up the sending of Ajax requests.
$.when($.get('assets/misc/1.json'), $.get('assets/misc/2.json')).then(function(r1, r2){ console.log(r1[0].message + " " + r2[0].message); })
16. Obtain ip through jQuery
We can not only ping ip to a website on the computer, but also get it through jQuery.
$.get('https://jsonip.com/', function(res){ console.log(res.ip); });
17. Use the simplest ajax request
jQuery (using ajax) provides a shorthand method to quickly download content and add it to an element.
<p class="content"></p> <p class="content"></p>
var contentDivs = $('.content'); contentDivs.eq(0).load('1.txt'); contentDivs.eq(1).load('1.html #header');
18. Geographical location by IP address
There are many online services that can tell us where the IP address is located in the city and country. Next, let's ping to Baidu's IP address and get its location.
var ip = '119.75.218.70', api = 'http://freegeoip.net/json/' + ip + '?callback=?'; $.getJSON(api, function(r){ console.log('How is the weather in ' + r.city + ', ' + r.country_name + '?'); });
19. Use anonymous functions to generate a separate block of code
Defining global variables and functions is a very rough code behavior, and a better way is to use anonymous functions to make your code independent of blocks. Look at the following examples:
(function($){ var c = 1; $.fn.count = function(){ log(c++); return this; }; })(jQuery); $(document).count(); $('body').count().count();
No...