以下是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;
});
如果您觉得本文的内容对您的学习有所帮助:
关键字:
DIV+CSS规范命名让你的前端设计更完善