jQuery 常用代码集锦(必看篇)


Posted in Javascript onMay 16, 2016

1. 选择或者不选页面上全部复选框

var tog = false; // or true if they are checked on load
$('a').click(function() {
 $("input[type=checkbox]").attr("checked",!tog);
 tog = !tog;
});

2. 取得鼠标的X和Y坐标

$(document).mousemove(function(e){
$(document).ready(function() {
$().mousemove(function(e){
$('#XY').html("Gbin1 X Axis : " + e.pageX + " | Gbin1 Y Axis " + e.pageY);
});
});

3. 判断一个图片是否加载完全

$('#theGBin1Image').attr('src', 'image.jpg').load(function() {
alert('This Image Has Been Loaded');
});

4. 判断cookie是否激活或者关闭

var dt = new Date();
dt.setSeconds(dt.getSeconds() + 60);
document.cookie = "cookietest=1; expires=" + dt.toGMTString();
var cookiesEnabled = document.cookie.indexOf("cookietest=") != -1;
if(!cookiesEnabled)
{
 //cookies have not been enabled
}

5. 强制过期cookie

var date = new Date();
date.setTime(date.getTime() + (x * 60 * 1000));
$.cookie('example', 'foo', { expires: date });

6. 在表单中禁用“回车键”,表单的操作中需要防止用户意外的提交表单

$("#form").keypress(function(e) {
 if (e.which == 13) {
 return false;
 }
});

7. 清除所有的表单数据

function clearForm(form) {
 // iterate over all of the inputs for the form
 // element that was passed in
 $(':input', form).each(function() {
 var type = this.type;
 var tag = this.tagName.toLowerCase(); // normalize case
 // it's ok to reset the value attr of text inputs,
 // password inputs, and textareas
 if (type == 'text' || type == 'password' || tag == 'textarea')
  this.value = "";
 // checkboxes and radios need to have their checked state cleared
 // but should *not* have their 'value' changed
 else if (type == 'checkbox' || type == 'radio')
  this.checked = false;
 // select elements need to have their 'selectedIndex' property set to -1
 // (this works for both single and multiple select elements)
 else if (tag == 'select')
  this.selectedIndex = -1;
 });
};

8.禁止多次递交表单

$(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;
 }
 });
});

9. 自动将数据导入selectbox中

$(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 += '<option value="' + j[i].optionValue + '">' + j[i].optionDisplay + '</option>';
  }
  $("select#ctlPerson").html(options);
 })
 })
})

10. 创建一个嵌套的过滤器

.filter(":not(:has(.selected))") //去掉所有不包含class为.selected的元素

11. 使用has()来判断一个元素是否包含特定的class或者元素

//jQuery 1.4.* includes support for the has method. This method will find 
//if a an element contains a certain other element class or whatever it is 
//you are looking for and do anything you want to them. 
$("input").has(".email").addClass("email_icon");

12. 使用jQuery切换样式

//Look for the media-type you wish to switch then set the href to your new style sheet 
$('link[media='screen']').attr('href', 'Alternative.css');

13. 如何正确使用ToggleClass

//Toggle class allows you to add or remove a class 
//from an element depending on the presence of that 
//class. Where some developers would use: 
a.hasClass('blueButton') ? a.removeClass('blueButton') : a.addClass('blueButton'); 
//toggleClass allows you to easily do this using 
a.toggleClass('blueButton');

14. 使用jQuery来替换一个元素

$('#thatdiv').replaceWith('fnuh');

15.绑定一个函数到一个事件

$('#foo').bind('click', function() { 
 alert('User clicked on "foo."'); 
});

16. 使用jQuery预加载图片

jQuery.preloadImages = function() { for(var i = 0; i').attr('src', arguments[i]); } }; 
// Usage $.preloadImages('image1.gif', '/path/to/image2.png', 'some/image3.jpg');

17. 设置任何匹配一个选择器的事件处理程序

$('button.someClass').live('click', someFunction);
 //Note that in jQuery 1.4.2, the delegate and undelegate options have been
 //introduced to replace live as they offer better support for context
 //For example, in terms of a table where before you would use..
 // .live()
 $("table").each(function(){
 $("td", this).live("hover", function(){
 $(this).toggleClass("hover");
 });
 });
 //Now use..
 $("table").delegate("td", "hover", function(){
 $(this).toggleClass("hover");
});

18. 自动的滚动到页面特定区域

jQuery.fn.autoscroll = function(selector) {
 $('html,body').animate(
 {scrollTop: $(selector).offset().top},

 );
}
//Then to scroll to the class/area you wish to get to like this:
$('.area_name').autoscroll();

19.检测各种浏览器

Detect Safari (if( $.browser.safari)),
Detect IE6 and over (if ($.browser.msie && $.browser.version > 6 )),
Detect IE6 and below (if ($.browser.msie && $.browser.version <= 6 )),
Detect FireFox 2 and above (if ($.browser.mozilla && $.browser.version >= '1.8' )

20.限制textarea的字符数量

jQuery.fn.maxLength = function(max){
 this.each(function(){
 var type = this.tagName.toLowerCase();
 var inputType = this.type? this.type.toLowerCase() : null;
 if(type == "input" && inputType == "text" || inputType == "password"){
  //Apply the standard maxLength
  this.maxLength = max;
 }
 else if(type == "textarea"){
  this.onkeypress = function(e){
  var ob = e || event;
  var keyCode = ob.keyCode;
  var hasSelection = document.selection? document.selection.createRange().text.length > 0 : this.selectionStart != this.selectionEnd;
  return !(this.value.length >= max && (keyCode > 50 || keyCode == 32 || keyCode == 0 || keyCode == 13) && !ob.ctrlKey && !ob.altKey && !hasSelection);
  };
  this.onkeyup = function(){
  if(this.value.length > max){
   this.value = this.value.substring(0,max);
  }
  };
 }
 });
};
//Usage:
$('#gbin1textarea').maxLength(500);

21.使用jQuery克隆元素

var cloned = $('#gbin1div').clone();

22. 元素屏幕居中

jQuery.fn.center = function () {
 this.css('position','absolute');
 this.css('top', ( $(window).height() - this.height() ) / +$(window).scrollTop() + 'px');
 this.css('left', ( $(window).width() - this.width() ) / 2+$(window).scrollLeft() + 'px');return this;
}
//Use the above function as: $('#gbin1div').center();

23 .简单的tab标签切换

jQuery('#meeting_tabs ul li').click(function(){
  jQuery(this).addClass('tabulous_active').siblings().removeClass('tabulous_active');
  jQuery('#tabs_container>.pane:eq('+jQuery(this).index()+')').show().siblings().hide(); 
 })

<div id="meeting_tabs">
    <ul>
      <li class="tabulous_active"><a href="#" title="">进行中</a></li>
      <li><a href="#" title="">未开始</a></li>
      <li><a href="#" title="">已结束</a></li>
      <li><a href="#" title="">全部</a></li>
     </ul>
 <div id="tabs_container">
   <div class="pane"  >1</div>
   <div class="pane"  >2</div>
   <div class="pane"  >3</div>
   <div class="pane"  >4</div>
 </div>
</div>

以上这篇jQuery 常用代码集锦(必看篇)就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持三水点靠木。

Javascript 相关文章推荐
教你如何解密js/vbs/vbscript加密的编码异处理小结
Jun 25 Javascript
jQuery 数据缓存data(name, value)详解及实现
Jan 04 Javascript
jquery对表单操作2
Apr 06 Javascript
js实现的二级横向菜单条实例
Aug 22 Javascript
使用jQuery实现WordPress中的Ctrl+Enter和@评论回复
May 21 Javascript
javascript之Boolean类型对象
Jun 07 Javascript
js实现浏览器倒计时跳转页面效果
Aug 12 Javascript
浅谈JS中的三种字符串连接方式及其性能比较
Sep 02 Javascript
jQuery实现鼠标选中文字后弹出提示窗口效果【附demo源码】
Sep 05 Javascript
js中的触发事件对象event.srcElement与event.target详解
Mar 15 Javascript
jQuery实现判断滚动条滚动到document底部的方法分析
Aug 27 jQuery
解决Vue-cli3没有vue.config.js文件夹及配置vue项目域名的问题
Dec 04 Vue.js
阻止表单提交按钮多次提交的完美解决方法
May 16 #Javascript
js判断登陆用户名及密码是否为空的简单实例
May 16 #Javascript
javascript实现起伏的水波背景效果
May 16 #Javascript
JavaScript判断用户名和密码不能为空的实现代码
May 16 #Javascript
JS闭包、作用域链、垃圾回收、内存泄露相关知识小结
May 16 #Javascript
js流动式效果显示当前系统时间
May 16 #Javascript
JavaScript禁止复制与粘贴的实现代码
May 16 #Javascript
You might like
PHP基于CURL进行POST数据上传实例
2014/11/10 PHP
PHP基于DateTime类解决Unix时间戳与日期互转问题【针对1970年前及2038年后时间戳】
2018/06/13 PHP
用php定义一个数组最简单的方法
2019/10/04 PHP
把html页面的部分内容保存成新的html文件的jquery代码
2009/11/12 Javascript
JavaScript 序列化对象实现代码
2009/12/18 Javascript
javascript SpiderMonkey中的函数序列化如何进行
2012/12/05 Javascript
jquery实现的导航固定效果
2014/04/28 Javascript
jquery中each遍历对象和数组示例
2014/08/05 Javascript
Bootstrap 下拉多选框插件Bootstrap Multiselect
2017/01/22 Javascript
JS及JQuery对Html内容编码,Html转义
2017/02/17 Javascript
JavaScript变量作用域_动力节点Java学院整理
2017/06/27 Javascript
微信小程序实现鼠标拖动效果示例
2017/12/01 Javascript
解决vue中使用Axios调用接口时出现的ie数据处理问题
2018/08/13 Javascript
nodejs初始化init的示例代码
2018/10/10 NodeJs
原生JS实现天气预报
2020/06/16 Javascript
Python中给List添加元素的4种方法分享
2014/11/28 Python
Python中用max()方法求最大值的介绍
2015/05/15 Python
Python 创建新文件时避免覆盖已有的同名文件的解决方法
2018/11/16 Python
Python实现Restful API的例子
2019/08/31 Python
python SVD压缩图像的实现代码
2019/11/05 Python
Python 实现数组相减示例
2019/12/27 Python
Python3之乱码\xe6\x97\xa0\xe6\xb3\x95处理方式
2020/05/11 Python
html5拍照功能实现代码(htm5上传文件)
2013/12/11 HTML / CSS
HTML块级标签汇总(小篇)
2016/07/13 HTML / CSS
德国旅游网站:weg.de
2018/06/03 全球购物
英国123鲜花网站:123 Flowers
2019/07/07 全球购物
一家专门经营包包的英国网站:MyBag
2019/09/08 全球购物
俄罗斯购买自行车网站:Vamvelosiped
2021/01/29 全球购物
康拓普公司Java笔面试
2016/09/23 面试题
预备党员转正考核材料
2014/06/03 职场文书
小区推广策划方案
2014/06/06 职场文书
医院见习报告范文
2014/11/03 职场文书
幼儿教师2014年度工作总结
2014/12/16 职场文书
2016入党培训心得体会范文
2016/01/08 职场文书
golang中的空接口使用详解
2021/03/30 Python
python数字图像处理:图像的绘制
2022/06/28 Python