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 相关文章推荐
javascript 关闭IE6、IE7
Jun 01 Javascript
js 第二代身份证号码的验证机制代码
May 12 Javascript
基于jquery的一个拖拽到指定区域内的效果
Sep 21 Javascript
js改变img标签的src属性在IE下没反应的解决方法
Jul 23 Javascript
JQuery对class属性的操作实现按钮开关效果
Oct 11 Javascript
浅谈Javascript中匀速运动的停止条件
Dec 19 Javascript
在JavaScript中处理数组之reverse()方法的使用
Jun 09 Javascript
JS异步文件分片断点上传的实现思路
Dec 25 Javascript
vue mounted组件的使用
Jun 18 Javascript
Egg.js 中 AJax 上传文件获取参数的方法
Oct 10 Javascript
JS 实现获取验证码 倒计时功能
Oct 29 Javascript
Vue中通过Vue.extend动态创建实例的方法
Aug 13 Javascript
阻止表单提交按钮多次提交的完美解决方法
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的加载类操作以及其他两种魔术方法的应用实例
2017/08/28 PHP
PHP实现的链式队列结构示例
2017/09/15 PHP
Laravel路由研究之domain解决多域名问题的方法示例
2019/04/04 PHP
千分位数字格式化(用逗号隔开 代码已做了修改 支持0-9位逗号隔开)的JS代码
2013/12/05 Javascript
jquery中event对象属性与方法小结
2013/12/18 Javascript
关闭页面window.location事件未执行的原因及解决方法
2014/09/01 Javascript
javascript检测浏览器的缩放状态实现代码
2014/09/28 Javascript
Jquery插件实现点击获取验证码后60秒内禁止重新获取
2015/03/13 Javascript
JS+DIV+CSS实现仿表单下拉列表效果
2015/08/18 Javascript
Vue.js基础学习之class与样式绑定
2017/03/20 Javascript
vue+ElementUI实现订单页动态添加产品数据效果实例代码
2017/07/13 Javascript
基于jquery实现多选下拉列表
2017/08/02 jQuery
jQuery简单实现向列表动态添加新元素的方法示例
2017/12/25 jQuery
js+html5实现手机九宫格密码解锁功能
2018/07/30 Javascript
Node.js npm命令运行node.js脚本的方法
2018/10/10 Javascript
JS与SQL方式随机生成高强度密码示例
2018/12/29 Javascript
vue实现todolist功能、todolist组件拆分及todolist的删除功能
2019/04/11 Javascript
Vue中全局变量的定义和使用
2019/06/05 Javascript
微信小程序全局变量GLOBALDATA的定义和调用过程解析
2019/09/23 Javascript
vue-router结合vuex实现用户权限控制功能
2019/11/14 Javascript
如何构建 vue-ssr 项目的方法步骤
2020/08/04 Javascript
python dict remove数组删除(del,pop)
2013/03/24 Python
python获取从命令行输入数字的方法
2015/04/29 Python
在主机商的共享服务器上部署Django站点的方法
2015/07/22 Python
Python数据可视化教程之Matplotlib实现各种图表实例
2019/01/13 Python
【python】matplotlib动态显示详解
2019/04/11 Python
Ubuntu中配置TensorFlow使用环境的方法
2020/04/21 Python
使用Keras实现Tensor的相乘和相加代码
2020/06/18 Python
python中四舍五入的正确打开方式
2021/01/18 Python
西班牙香水和化妆品网上商店:Douglas
2017/10/29 全球购物
PHP中如何使用Cookie
2015/10/28 面试题
UML设计模式笔试题
2014/06/07 面试题
写好求职应聘自荐信的三部曲
2013/09/21 职场文书
工业设计专业自荐书
2014/06/05 职场文书
初中美术教学反思
2016/02/17 职场文书
小程序自定义轮播图圆点组件
2022/06/25 Javascript