Tips and tricks for 20 popular jquery

Source: Internet
Author: User

Here are some very useful jquery tips and all of jquery's development tips.

1. Optimize the choice of complex performanceQuerying a subset of the DOM dramatically improves performance when using complex choices:
var subset = $ (""); $ ("input[value^="] ", subset);
2. Setting context and improving performance
The jquery core functionality specifies the context parameters. Specifies the context parameter, which allows a deeper branch from the DOM, rather than starting from the DOM root, jquery. Given a DOM that is large enough, the specified context parameter translates into a performance boost.
$ ("Input:radio", Document.forms[0]);

3. Field event handlers

Set any one of the selected elements to match the event handler, even if it is added after the initial page is loaded into the DOM:
$ (' Button.someclass '). Live (' click ', someFunction);

This allows you to load content via Ajax, or add event handlers via JavaScript to set up these elements correctly and automatically. Similarly, to stop field event handling:
4. Check indexjquery has an index, but it's a pain to use the list of elements you need and the metrics you want through the elements

var index = e.g $ (' #ul >li '). Index (Lidomobject);
The following are relatively easy: $ ("ul > Li"). Click (function () {var index = $ (this). Prevall (). length;}); If you want to know the index of a collection element, such as a list item in an unordered table: 5. Ways to use data from jqueryThe jquery data () method is useful and not well known. It lets you eliminate the need to modify the DOM binding data to DOM elements. $ ("ul > Li"). Click (function () {var index = $ (this). Prevall (). length;}); 6. remove the fade effect of an element basic show effectCombine multiple jquery effects, animate and delete dom elements.

$ ("#myButton"). Click (function () {$ ("#myDiv"). FadeTo ("Slow", 0.01, function () {//fade $ (this). Slideup (         "Slow", function () {//slide-$ (this). Remove ();//then remove from the DOM}); });}); 7. Checks if an element exists
if ($( "#someDiv" ).length) {      //hooray!!! it exists... }

Use the following code snippet to check whether an element exists or not.

8. Dynamically created elements added to the DOM

Use the following code snippet to dynamically create a div and add it to the DOM. var newDiv = $( ‘<div></div>‘ );

newDiv.attr("id","myNewDiv").appendTo("body");

9. Line break and chainability.

Rather than doing:

$( "a" ).hide().addClass().fadeIn().hide();

像这样可以增加可读性:
$( "a" )    .hide()    .addClass()    .fadeIn()    .hide();

10。创建自定义选择

$.extend($.expr[ ‘:‘ ], {      over100pixels:  function (a) {          return $(a).height() > 100;      } }); $( ‘.box:over100pixels‘ ).click( function () {      alert( ‘The element you clicked is over 100 pixels high‘ ); });

11. Cloning in a jquery object

Use the Clone () method. The jquery method clones the DOM object in any JavaScript.

// Clone the DIV var cloned = $( ‘#somediv‘ ).clone();
jQuery的clone()方法不克隆一个JavaScript对象。克隆JavaScript对象,使用下面的代码。
// Shallow copy var newObject = jQuery.extend({}, oldObject); // Deep copy var newObject = jQuery.extend( true , {}, oldObject);

12. Test if things are hidden using jquery

We use. Hide (). In the jquery Show () method to change the visibility of the element. Use the following code to check whether an element is visible or invisible. if ($(element).is( ":visible" ) ==  "true" ) {         //The element is Visible }
13。另一种方式的文件准备就绪

//Instead of $(document).ready( function () {      //document ready }); //Use $( function (){      //document ready });

14. Select an element. (period), in its ID

Select the element that uses the backslash to select during its ID.
$( "#Address\\.Street" ).text( "Enter this field" );

15. Direct child elements of a count

If you want to calculate all the div#foo elements that exist in
<div id= "foo" > <div id= "Bar" ></div> <div id= "baz" > <div id= "Biz" > </div> <sp An><span></div>//jquery code to count child elements$ ("#foo > div"). Size ()
16. Make a "flash" element

jQuery.fn.flash =  function ( color, duration ) {      var current =  this .css(  ‘color‘ );      this .animate( { color:  ‘rgb(‘ + color +  ‘)‘ }, duration / 2 );      this .animate( { color: current }, duration / 2 ); } //Then use the above function as: $(  ‘#importantElement‘ ).flash(  ‘255,0,0‘ , 1000 );
17。中心元素在屏幕上

jQuery.fn.center =  function () {      this .css( "position" , "absolute" );      this .css( "top" , ( $(window).height() -  this .height() ) / 2+$(window).scrollTop() +  "px" );      this .css( "left" , ( $(window).width() -  this .width() ) / 2+$(window).scrollLeft() +  "px" );      return this ; } //Use the above function as: $(element).center();
18. Gets the parent div using the closest

If you want to find the wrapping paper div element (regardless of the DIV's id), then you will want to choose this jquery:
$( "#searchBox" ).closest( "div" );

19. Disable Right-click context menu

There are also many JavaScript fragments that are disabled right-click
Click the context menu, but jquery makes things a lot easier:

$(document).ready( function (){      $(document).bind( "contextmenu" , function (e){          return false ;      });

});

20. Gets the x and y axes of the mouse cursor

This script displays the X and Y values-the coordinates of the mouse pointer.

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.