jQuery 常用代碼集錦(必看篇)
來源:易賢網(wǎng) 閱讀:885 次 日期:2016-06-29 15:13:34
溫馨提示:易賢網(wǎng)小編為您整理了“jQuery 常用代碼集錦(必看篇)”,方便廣大網(wǎng)友查閱!

下面小編就為大家?guī)硪黄猨Query 常用代碼集錦(必看篇)。小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考

1. 選擇或者不選頁(yè)面上全部復(fù)選框

var tog = false; // or true if they are checked on load

$('a').click(function() {

 $("input[type=checkbox]").attr("checked",!tog);

 tog = !tog;

});

2. 取得鼠標(biāo)的X和Y坐標(biāo)

$(document).mousemove(function(e){

$(document).ready(function() {

$().mousemove(function(e){

$('#XY').html("Gbin1 X Axis : " + e.pageX + " | Gbin1 Y Axis " + e.pageY);

});

});

3. 判斷一個(gè)圖片是否加載完全

$('#theGBin1Image').attr('src', 'image.jpg').load(function() {

alert('This Image Has Been Loaded');

});

4. 判斷cookie是否激活或者關(guān)閉

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. 強(qiáng)制過期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. 清除所有的表單數(shù)據(jù)

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. 自動(dòng)將數(shù)據(jù)導(dǎo)入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. 創(chuàng)建一個(gè)嵌套的過濾器

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

11. 使用has()來判斷一個(gè)元素是否包含特定的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來替換一個(gè)元素

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

15.綁定一個(gè)函數(shù)到一個(gè)事件

$('#foo').bind('click', function() { 

 alert('User clicked on "foo."'); 

});

16. 使用jQuery預(yù)加載圖片

jQuery.preloadImages = function() { for(var i = 0; i').attr('src', arguments[i]); } }; 

// Usage $.preloadImages('image1.gif', '/path/to/image2.png', 'some/image3.jpg');

17. 設(shè)置任何匹配一個(gè)選擇器的事件處理程序

$('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. 自動(dòng)的滾動(dòng)到頁(yè)面特定區(qū)域

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.檢測(cè)各種瀏覽器

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的字符數(shù)量

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 .簡(jiǎn)單的tab標(biāo)簽切換

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="">進(jìn)行中</a></li>

      <li><a href="#" title="">未開始</a></li>

      <li><a href="#" title="">已結(jié)束</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 常用代碼集錦(必看篇)就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考

更多信息請(qǐng)查看網(wǎng)絡(luò)編程
易賢網(wǎng)手機(jī)網(wǎng)站地址:jQuery 常用代碼集錦(必看篇)
由于各方面情況的不斷調(diào)整與變化,易賢網(wǎng)提供的所有考試信息和咨詢回復(fù)僅供參考,敬請(qǐng)考生以權(quán)威部門公布的正式信息和咨詢?yōu)闇?zhǔn)!

2025國(guó)考·省考課程試聽報(bào)名

  • 報(bào)班類型
  • 姓名
  • 手機(jī)號(hào)
  • 驗(yàn)證碼
關(guān)于我們 | 聯(lián)系我們 | 人才招聘 | 網(wǎng)站聲明 | 網(wǎng)站幫助 | 非正式的簡(jiǎn)要咨詢 | 簡(jiǎn)要咨詢須知 | 新媒體/短視頻平臺(tái) | 手機(jī)站點(diǎn) | 投訴建議
工業(yè)和信息化部備案號(hào):滇ICP備2023014141號(hào)-1 云南省教育廳備案號(hào):云教ICP備0901021 滇公網(wǎng)安備53010202001879號(hào) 人力資源服務(wù)許可證:(云)人服證字(2023)第0102001523號(hào)
云南網(wǎng)警備案專用圖標(biāo)
聯(lián)系電話:0871-65099533/13759567129 獲取招聘考試信息及咨詢關(guān)注公眾號(hào):hfpxwx
咨詢QQ:1093837350(9:00—18:00)版權(quán)所有:易賢網(wǎng)
云南網(wǎng)警報(bào)警專用圖標(biāo)