JQuery tips and tips
Tips for using JQ:
1. is () method
Checks Matching Element Sets Based on selectors, elements, or jQuery objects. if at least one element matches a given parameter, true is returned. 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, the write click event is triggered only after the list item li itself is clicked.
It can also make the following judgments:
// Whether it is a divelem. is ('div ') & console. log ("it's a div"); // is there an element that contains (or can have other class names) the class name of bigbox? Elem. is ('. bigbox') & console. log ("it has the bigbox class! "); // Is it hidden? Elem. is (': not (: visible)') & console. log ("it is den! ");
Note that the & operator can be used to make a judgment. When the current condition is met, it will be executed later. However, the following condition cannot be an expression but can only be a console. log () or I.
There are also the following useful usage:
Elem. animate ({'width': 200}, 1000); // whether or not elem. is (': animated') & console. log ("it is animated! ");
2. Expansion Method in jquery
$. Fn refers to the namespace of jquery. Adding Methods and attributes on fn will be effective for each jquery instance.
For example, extend $. fn. abc (), that is, $. fn. abc () is an extension of the abc method for jquery, so every jquery instance can reference this method later.
Then you can: $ ("# div"). abc ();
JQuery. extend (object); adds a new method to the class to extend the jQuery class itself.
JQuery. fn. extend (object); add a method to the jQuery object.
JQuery. extend (object); adding class methods to the jQuery class can be understood as adding static methods. For example:
Elem. animate ({'width': 200}, 1000); // whether or not elem. is (': animated') & console. log ("it is animated! ");
Add a "static method" for jQuery as add, and then you can use this method in the place 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 limit the search result given by the first parameter.
$ ('<Div>', {"class": "bigBlue", "css": {"background-color": "purple"}, "width": 20, "height": 20, "animate": {// you can set the div animation effect "width": 200, "height": 50 }}). appendTo ('# result ');
Here, the second parameter is used to set the created element.
4. The end () method in jquery can make the chain syntax more efficient and fast to write.
<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 the upper level of the search element.
5. Right-click the contextmenu event
You may want a web application to feel more like a native one, so it can block the default contextmenu event.
$(function(){ $(document).on("contextmenu",function(e){ e.preventDefault(); });});
Of course, you can also customize the application of this event. The right-click operation menu is similar
6. Sometimes we do not want a part of the content of a webpage 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, the content cannot be selected again.
7. Minimal DOM operation
Using JavaScript to operate DOM is a waste of resources. The following method is generally used:
var elem = $('#elem');for(var i = 0; i < 100; i++){ elem.append('<li>element '+i+'</li>');}
In this way, repeated addition to elements is undoubtedly a great waste of resources. The following method 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 URL Decomposition
We can use regular expressions to break down URLs, but this is not a good method. We can use the tag to break down 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 complete the URL decomposition.
9. Sometimes, caching selector can optimize your js
There are three situations below. The first case is the common practice of some people. This method is laborious and thankless. The second two schemes are the optimization of the first one. You can select either of them.
First:
$('#pancakes li').eq(0).remove();$('#pancakes li').eq(1).remove();$('#pancakes li').eq(2).remove();
The second and third types can be either of the following:
// Var pancakes =$ ('# pancakes li'); pancakes. eq (0 ). remove (); pancakes. eq (1 ). remove (); pancakes. eq (2 ). remove (); // The third type of 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 jQuery version 1.7, The on () method is a new alternative to the bind (), live (), and delegate () methods. This method brings a lot of convenience to the API. We recommend that you use this method, which simplifies the jQuery code base.
Note:The event handler added using the on () method applies to current and future elements (such as new elements created by scripts ).
Tip:To remove the event handler, use the off () method.
Tip:To add an event that only runs once and then remove it, use the one method.
$(selector).on(event,childSelector,data,function,map)
11. simulate a trigger event
Trigger can be used to trigger a click event.
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 event name we like and trigger it. Example:
<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 variablesvar ball = $('<div id="ball"></div>').appendTo('body'),startPosition = {}, elementPosition = {};// Listen for mouse and touch eventsball.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. Faster blocking of default events
Generally, we use event. preventDefalut () to stop default events, but jquery provides a simpler method for this:
<a href="http://google.com/" id="goToGoogle">Go To Google</a>
$('#goToGoogle').click(false);
14. Use event. result to link multiple event handlers.
It is not common to bind multiple event handlers to an element. Using event. result can also associate multiple event handlers. Let's look at the example below.
Var press = $ ('# press'); press. on ('click', function () {return 'hip ';}); press. on ('click', function (e) {console. log (e. result + 'hop! ');}) // Console output: HipHop!
15. run multiple Ajax requests in parallel
When we need to send multiple Ajax requests, instead of waiting for one sending to end before sending the next one, we can send them in parallel to accelerate 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. Get the ip address through jQuery
We can not only ping the ip address of a website on the computer, but also obtain
$.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. Obtain the geographic location through the IP address
There are a lot of online services that can tell us the city and country where the IP address is located. Next we will ping Baidu's IP address and then obtain its geographical 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 an independent code block
Defining global variables and functions is a rough code. A better way is to use anonymous functions to make your code independent from blocks. See the following example:
(function($){ var c = 1; $.fn.count = function(){ log(c++); return this; }; })(jQuery);$(document).count();$('body').count().count();
The above is all the content of this article. I hope this article will help you in your study or work. I also hope to provide more support to the customer's home!