以下是10個非常實用的jQuery代碼片段。實用這些代碼前,你需要將jQuery類庫導入web頁面,并且添加代碼到以下DOM ready功能內:
$(document).ready(function() { // add your snippets here });
1. 為IE6用戶顯示警告信息
if ( (jQuery.browser.msie) && (parseInt(jQuery.browser.version) < 7) ) { $('body').prepend('<div class="warning">You are using an old version of Internet Explorer which is not supported. Please upgrade your browser in order to view this website.</div>');}
2. Javascript可用時添加hasJS類到body標簽
$('body').addClass('hasJS');
3. 點擊后清除輸入框的內容
<input type="text" name="search" class="search" value="Keywords" title="Keywords" />$('input[type=text]').focus(function() { var title = $(this).attr('title'); if ($(this).val() == title) { $(this).val(''); }}).blur(function() { var title = $(this).attr('title'); if ($(this).val() == '') { $(this).val(title); }});
4. 點擊后顯示/隱藏更多內容
<p><a href="#how-to" class="toggle">How to write a good article?</a></p><div id="how-to"> How to tips go here.</div>$('a.toggle').toggle(function() { var id = $(this).attr("href"); $(this).addClass("active"); $(id).slideDown();}, function() { var id = $(this).attr("href"); $(this).removeClass("active"); $(id).slideUp();});
5. 打開打印機對話框
<a href="#" class="print">Print this page</a>$('a.print').click(function(){ window.print(); return false;});
6. 給table數據添加"hover" class
$('table').delegate('td', 'hover', function(){ $(this).toggleClass('hover');});
7. 如果rel設置為"external",在新窗口打開一個link
<a href="http://www.google.com" rel="external">Google</a>$('a[rel=external]').attr('target', '_blank');
8. 添加奇數行class來區分table行(改變table奇偶行背景色以達到區分行效果)
$('tr:odd').addClass('odd');
9. 檢查是否div存在于頁面
if ( $('#myDiv').length ) { // do something with myDiv}
10. 選中/不選中所有的復選框
<div class="options"> <ul> <li><a href="#" class="select-all">Select All</a></li> <li><a href="#" class="reset-all">Reset All</a></li> </ul> <input type="checkbox" id="option1" /><label for="option1">Option 1</label> <input type="checkbox" id="option2" /><label for="option2">Option 2</label> <input type="checkbox" id="option3" /><label for="option3">Option 3</label> <input type="checkbox" id="option4" /><label for="option4">Option 4</label></div>$('.select-all').live('click', function(){ $(this).closest('.options').find('input[type=checkbox]').attr('checked', true); return false;});$('.reset-all').live('click', function(){ $(this).closest('.options').find('input[type=checkbox]').attr('checked', false); return false;});