几个可以直接拿来用的jQuery代码片段

jQuery里提供了许多创建交互式网站的方法,外国网站上蛮多现成的代码的,选了几个不错的分享一下。

预加载图片

(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);
    }
  }
jQuery.preLoadImages("image1.gif", "/path/to/image2.png");

 源码

移动设备上的自适应

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(){
    $('div').attr('class', '').attr('id', '').css({
        'margin' : 0,
        'padding' : 0,
        'width': '100%',
        'clear':'both'
    });
};

 源码

返回顶部

// Back To Top
$(document).ready(function(){
  $('.top').click(function() { 
     $(document).scrollTo(0,500); 
  });
});
//Create a link defined with the class .top
<a href="#" class="top">Back To Top</a>

 源码

自动填充选择框

$(function(){
$("select#ctlJob").change(function(){
$.getJSON("/select.php",{id: $(this).val(), ajax: 'true'}, function(j){
var options = '';
for (var i = 0; i < j.length; i++) {
options += '
' + j[i].optionDisplay + '
';
}
$("select#ctlPerson").html(options);
})
})
})

 源码

阻止表单多次提交

$(document).ready(function() {
  $('form').submit(function() {
    if(typeof jQuery.data(this, "disabledOnSubmit") == 'undefined') {
      jQuery.data(this, "disabledOnSubmit", { submited: true });
      $('input[type=submit], input[type=button]', this).each(function() {
        $(this).attr("disabled", "disabled");
      });
      return true;
    }
    else
    {
      return false;
    }
  });
});

 源码

 

原文地址:https://www.cnblogs.com/uncleshu/p/3197833.html