加入收藏 | 设为首页 | 会员中心 | 我要投稿 核心网 (https://www.hxwgxz.com/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 业界 > 正文

10个实用的jQuery代码片段

发布时间:2018-08-28 18:06:28 所属栏目:业界 来源:站长网
导读:以下是10个非常实用的 jQuery 代码片段。实用这些代码前,你需要将jQuery类库导入web页面,并且添加代码到以下DOM ready功能内: $(document).ready(function() { // add your snippets here }); 1. 为IE6用户显示警告信息 if ( (jQuery.browser.msie) (pa

以下是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;
});

(编辑:核心网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    热点阅读