11个常用的和基础的 jQuery 代码片段

jopen 10年前

在这篇文章中,我们将重点放在11个基本的和广泛使用的jQuery代码片段。

Print Page Option:

The Print Page Option is a jQuery plugin that eases a developer’s arduous task of providing options for the print page. The code snippet is as follows:

<!-- jQuery: Print Page -->  $('a.printPage').click(function(){             window.print();             return false;  });   <!-- HTML: Print Page -->  <div>     <a class="printPage" href="#">Print</a>  </div>

2. Preloading Images:

As the name suggests, Preloading Images is a jQuery plugin that helps developers preload images into webistes without having to write long codes. The code looks something like this –

(function($) {    var cache = [];    // Arguments are image paths relative to the current page.    $.preLoadImages = function() {      var args_len = arguments.length;      for (var i = args_len; i--;) {        var cacheImage = document.createElement('img');        cacheImage.src = arguments[i];        cache.push(cacheImage);      }    }

3. Hover On/Off:

This jQuery plugin can be used to bind two handlers to the matched elements which can be executed when the mouse pointer enters and leaves the prescribed elements. Let’s take a look at the code snippet –

$("a").hover(    function () {      // code on hover over    },    function () {      // code on away from hover    }  );

4. Helping Input Field/Swap Input Field:

When a website provides comment’s section or forms that have to be filled by the user, you can sometimes come across some Input Text field where some default text is shown but which disappears when the user clicks on it to enter a value. This can be easily done with the help of the following code snippet –

<!-- jQuery: Helping Input Field -->  $('input[type=text]').focus(function(){                 var $this = $(this);             var title = $this.attr('title');             if($this.val() == title)             {                 $this.val('');             }  }).blur(function() {             var $this = $(this);             var title = $this.attr('title');             if($this.val() == '')             {                 $this.val(title);             }  });  <!-- HTML: Swap Input Field -->  <div>           </div>

5. Make Everything Mobile Friendly:

It has become absolutely necessary to websites to be responsive and mobile friendly. Luckily there is a jQuery code that can be used for this purpose. Let’s take a look –

var scr = document.createElement('script');  scr.setAttribute('src', 'https://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js');  document.body.appendChild(scr);    scr.onload = function(){

6. Scroll to Top:

‘Scroll to top’ has become a common phenomenon in websites where with the help of a simple link or button, users can go to the top of the page.

$("a[href='#top']").click(function() {    $("html, body").animate({ scrollTop: 0 }, "slow");    return false;  });

7. Select/Deselect All Options:

Using this jQuery code, developers can easily create checkboxes for selecting and deselecting options in the web page.

<!-- jQuery: Select/Deselect All -->  $('.SelectAll').live('click', function(){  $(this).closest('.divAll').find('input[type=checkbox]').attr('checked', true);  return false; });  $('.DeselectAll').live('click', function(){  $(this).closest('.divAll').find('input[type=checkbox]').attr('checked', false);  return false; });  <!-- HTML: Select/Deselect All -->  <div class="divAll">  <a href="#" class="SelectAll">Select All</a>     <a href="#" class="DeselectAll">Deselect All</a>  <br />  \  <label for="Lahore">Lahore</label>    <label for="Karachi">Karachi</label>    <label for="Islamabad">Islamabad</label> </div>

8. Image Resizing:

jQuery also has a code plugin for image resizing. Now you do not need to worry about the image size and resolution when uploading the same into the website.

$(window).bind("load", function() {   // IMAGE RESIZE   $('#product_cat_list img').each(function() {    var maxWidth = 120;    var maxHeight = 120;    var ratio = 0;    var width = $(this).width();    var height = $(this).height();      if(width &gt; maxWidth){     ratio = maxWidth / width;     $(this).css("width", maxWidth);     $(this).css("height", height * ratio);     height = height * ratio;    }    var width = $(this).width();    var height = $(this).height();    if(height &gt; maxHeight){     ratio = maxHeight / height;     $(this).css("height", maxHeight);     $(this).css("width", width * ratio);     width = width * ratio;    }   });   //$("#contentpage img").show();   // IMAGE RESIZE  }); 

9. Ajax Template:

jQuery is very commonly used for passing form data using AJAX. To make the process simpler, you can also use the following code –

$.ajax({    type: 'POST',    url: 'backend.php',    data: "q="+myform.serialize(),    success: function(data){      // on success use return data here    },    error: function(xhr, type, exception) {       // if ajax fails display error alert      alert("ajax error response type "+type);    }  });

10. Disabling Right Click:

Many websites prefer disabling the right click and to do so rightfully, here’s the jQuery code –

<!-- jQuery: Disabling Right Click -->  $(document).bind("contextmenu",function(e){         e.preventDefault();       }); 

11. Emulate 非死book by Preloading Previous & Next Photo Gallery Images:

非死book has become an integral part of the Internet and website do not want to lag behind in emulating 非死book. Here’s what jQuery code does for preloading previous and next photo gallery images –

var nextimage = "/images/some-image.jpg";  $(document).ready(function(){  window.setTimeout(function(){  var img = $("").attr("src", nextimage).load(function(){  //all done  });  }, 100);  });