Home > Web Front-end > JS Tutorial > body text

jQuery tips and tricks you can't learn elsewhere (welcome to collect)_jquery

WBOY
Release: 2016-05-16 15:19:13
Original
1153 people have browsed it

The editor below has compiled 8 tips that are very helpful for programmers. The details are as follows:

1) Disable mouse right click

jQuery programmers can use this code to disable right mouse clicks on web pages.

$(document).ready(function() {
//catch the right-click context menu
$(document).bind("contextmenu",function(e) { 
//warning prompt - optional
alert("No right-clicking!");
//delete the default context menu
return false;
});
});
Copy after login

2) Use jQuery to adjust text size

Using this code, users can resize (increase and decrease) the text on the website

$(document).ready(function() {
//find the current font size
var originalFontSize = $('html').css('font-size');
//Increase the text size
$(".increaseFont").click(function() {
var currentFontSize = $('html').css('font-size');
var currentFontSizeNumber = parseFloat(currentFontSize, 10);
var newFontSize = currentFontSizeNumber*1.2;
$('html').css('font-size', newFontSize);
return false;
});
//Decrease the Text Size
$(".decreaseFont").click(function() {
var currentFontSize = $('html').css('font-size');
var currentFontSizeNum = parseFloat(currentFontSize, 10);
var newFontSize = currentFontSizeNum*0.8;
$('html').css('font-size', newFontSize);
return false;
});
// Reset Font Size
$(".resetFont").click(function(){
$('html').css('font-size', originalFontSize);
});
});
Copy after login

3) Open the link in new Windows

 Try this code and increase your site impressions because using this jquery code users will go on new window after clicking on any link of your site. Code is below: -

$(document).ready(function() {
//select all anchor tags that have http in the href
//and apply the target=_blank
$("a[href^='http']").attr('target','_blank');
});
Copy after login

4) Style Sheets Swap

Swap style sheets using this code and the “Style sheets swap” script is below: -

$(document).ready(function() {
$("a.cssSwap").click(function() { 
//swap the link rel attribute with the value in the rel 
$('link[rel=stylesheet]').attr('href' , $(this).attr('rel')); 
}); 
});
Copy after login

5) Back to top link

 That is very common function you can see on eve site nowadays is ” Back to Top”. This functionality is very useful for long pages for make short in a single click. Visit this code below: -

$(document).ready(function() {
//when the id="top" link is clicked
$('#top').click(function() {
//scoll the page back to the top
$(document).scrollTo(0,500);
}
});
Copy after login

6) Get the x and y axes of the mouse cursor

You can find the values ​​of X and Y coordinator of mouse pointer. Code is blow : -

$().mousemove(function(e){
//display the x and y axis values inside the P element
$('p').html("X Axis : " + e.pageX + " | Y Axis " + e.pageY);
});
Copy after login

7) Detect current mouse coordinates

Using this script, you can find the current mouse coordinates in any web browser supported by jQuery. The code is as follows:

$(document).ready(function() {
$().mousemove(function(e)
{
$('# MouseCoordinates ').html("X Axis Position = " + e.pageX + " and Y Axis Position = " + e.pageY);
});
});
Copy after login

8) Preload images in jQuery

This image preloading script helps to load images or web pages very quickly. You don't have to wait for the image to load. Code:

jQuery.preloadImagesInWebPage = function() 
{
for(var ctr = 0; ctr<arguments.length; ctr++)
{
jQuery("<img alt="">").attr("src", arguments[ctr]);
}
}
To use the above method, you can use the following piece of code:
$.preloadImages("image1.gif", "image2.gif", "image3.gif");
To check whether an image has been loaded, you can use the following piece of code:
$('#imageObject').attr('src', 'image1.gif').load(function() {
alert('The image has been loaded…');
}); 
Copy after login

Do the following to ensure your jQuery performance is greatly improved

1. Append Outside of Loops

Anything involving the DOM has a price. If you're appending a lot of elements to the DOM, you'll want to append them all at once rather than doing it multiple times. A common problem arises when appending elements to a loop.

$.each( myArray, function( i, item ) {
var newListItem = "<li>" + item + "</li>";
$( "#ballers" ).append( newListItem );
}); 
Copy after login

A common technique is to use document fragments. On each iteration of the loop, append the element to the fragment instead of the DOM element. When the loop ends, append the fragment to the DOM element.

var frag = document.createDocumentFragment();
$.each( myArray, function( i, item ) {
var newListItem = document.createElement( "li" );
var itemText = document.createTextNode( item );
newListItem.appendChild( itemText );
frag.appendChild( newListItem );
});
$( "#ballers" )[ ].appendChild( frag ); 
Copy after login

Another simple trick is to continuously build a string on each iteration of the loop. When the loop ends, set the HTML of the DOM element to this string.

var myHtml = "";
$.each( myArray, function( i, item ) {
myHtml += "<li>" + item + "</li>";
});
$( "#ballers" ).html( myHtml ); 
Copy after login

Of course there are other techniques you can try. A site called jsperf provides a good outlet for testing these properties. The site allows you to benchmark each technique and visualize its cross-platform performance results.

2. Cache Length During Loops

In the for loop, do not access the length property of the array every time; it should be cached in advance.

var myLength = myArray.length;
for ( var i = ; i < myLength; i++ ) {
// do stuff
} 
Copy after login

3. Detach Elements to Work with Them

Manipulating the DOM is slow, so you want to do it with as little alignment as possible. jQuery introduced a method called detach() in version 1.4 to help solve this problem, which allows you to detach elements from the DOM when operating on them.

var $table = $( "#myTable" );
var $parent = $table.parent();
$table.detach();
// ... add lots and lots of rows to table
$parent.append( $table ); 
Copy after login

4. Don't Act on Absent Elements

If you are planning to run a lot of code on an empty selector, jQuery will not give you any hints - it will continue to execute as if no errors occurred. It's up to you to verify how many elements the selector contains.

// Bad: This runs three functions before it
// realizes there's nothing in the selection
$( "#nosuchthing" ).slideUp();
// Better:
var $mySelection = $( "#nosuchthing" );
if ( $mySelection.length ) {
$mySelection.slideUp();
}
// Best: Add a doOnce plugin.
jQuery.fn.doOnce = function( func ) {
this.length && func.apply( this );
return this;
}
$( "li.cartitems" ).doOnce(function() {&#8232;
// make it ajax! \o/&#8232;
}); 
Copy after login

This guide is particularly useful for jQuery UI widgets that require a lot of overhead when the selector does not contain an element.

5. Optimize Selectors

Selector optimization is not as important as in the past, because many browsers implement the document.querySelectorAll() method and jQuery shifts the burden of the selector to the browser. But there are still some tips to keep in mind.

ID based selector

It's always best to start your selector with an ID.

// Fast:
$( "#container div.robotarm" );
// Super-fast:
$( "#container" ).find( "div.robotarm" ); 
Copy after login

采用 .find() 方法的方式将更加的快速,因为第一个选择器已经过处理,而无需通过嘈杂的选择器引擎 -- ID-Only的选择器已使用 document.getElementById() 方法进行处理,之所以快速,是因为它是浏览器的原生方法。

特异性

尽量详细的描述选择器的右侧,对于左侧则应反其道而行之。

// Unoptimized:
$( "div.data .gonzalez" );
// Optimized:
$( ".data td.gonzalez" ); 
Copy after login

尽量在选择器的最右侧使用 tag.class 的形式来描述选择器,而在左侧则尽量只使用 tag 或者 .class 。

避免过度使用特异性

$( ".data table.attendees td.gonzalez" );
// Better: Drop the middle if possible.
$( ".data td.gonzalez" ); 
Copy after login

去讨好“DOM”总是有利于提升选择器的性能,因为选择器引擎在搜寻元素时无需进行太多的遍历。

避免使用通用选择器

如果一个选择器明确或暗示它能在不确定的范围内进行匹配将会大大影响性能。

$( ".buttons > *" ); // Extremely expensive.
$( ".buttons" ).children(); // Much better.
$( ".category :radio" ); // Implied universal selection.
$( ".category *:radio" ); // Same thing, explicit now.
$( ".category input:radio" ); // Much better. 
Copy after login

6. Use Stylesheets for Changing CSS on Many Elements

假如你使用 .css() 方法来改变超过20个元素的CSS,应当考虑为页面添加一个样式标签作为替代,这样做可以提升将近60%的速度。

// Fine for up to elements, slow after that:
$( "a.swedberg" ).css( "color", "#ad" );
// Much faster:
$( "<style type=\"text/css\">a.swedberg { color: #ad }</style>")
.appendTo( "head" ); 
Copy after login

7. Don't Treat jQuery as a Black Box

把jQuery的源码当成文档,可以把它(http://bit.ly/jqsource)保存在你的收藏夹内,经常的查阅参考。

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 Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!