jquery 技巧积累

1.checkbox相关操作

(1)判断复选框是否选中

if ($('#checkBox').is(":checked")) {...}

(2)checkbox选中、取消

$('#checkBox').prop("checked", true);
$('#checkBox').prop("checked", false);

(3)判断多个checkbox是否全选中

if ($('.checkItem:checked').length == 0) {
      $('#checkAll').prop("checked", false);
 }
2.禁启用按钮
$("#somebutton").attr("disabled", true);//禁用
$("#submit-button").removeAttr("disabled");//启用

注:.attr(‘disabled’,false);这样写是不对的

3.is()方法

判断选择器、元素或 jQuery 对象来检测匹配元素集合,如果这些元素中至少有一个元素匹配给定的参数,则返回 true

$("ul").click(function(event) {
  var $target = $(event.target);
  if ( $target.is("li") ) {
    $target.css("background-color", "red");
  }
});

// 是不是一个div
elem.is('div') && console.log("it's a div");

// 是不是有包含(也可以有其他类名)bigbox的类名的元素?
elem.is('.bigbox') && console.log("it has the bigbox class!");

// 是不是隐藏的?
elem.is(':not(:visible)') && console.log("it is hidden!");

//是否在动画
elem.animate({'width':200},1000);
elem.is(':animated') && console.log("it is animated!");
4.jquery中的end()方法,可以让链式语法写起来更加高效,快捷.

定义:end() 方法结束当前链条中的最近的筛选操作,并将匹配元素集还原为之前的状态。

<ul id="meals"> <li> <ul class="breakfast"> <li class="eggs">No</li> <li class="toast">No</li> <li class="juice">No</li> </ul> </li> </ul>
breakfast.find('.eggs').text('Yes').end() // back to breakfast
.find('.toast').text('Yes').end().find('.juice').toggleClass('juice coffee').text('Yes');
5.contextmenu事件 右键点击

也许希望web 应用感觉更像原生的,那么可以阻止contextmenu默认事件。

$(function(){
    $(document).on("contextmenu",function(e){
        e.preventDefault();
    });
});    

当然,应用此事件,也可以自定义,右键出来的操作菜单,类似于

6.empty(),remove()和detach()的区别
<div id="box" style="height: 50px;background: red">
    <p id="p1" style="height: 40px;line-height: 40px;background: #f5f5f5">111111</p>
</div>

empty():清空子节点,和子节点绑定的事件,自身不会被删除

$('#box').click(function () {
      console.log('box')
    })
    $('#p1').click(function () {
      console.log('p1')
    })

    apple = $("#p1");
    $("#box").empty();
    $('#box').append(apple);

remove():移除被选元素,包括所有文本和子节点,不会把匹配的元素从 jQuery 对象中删除,但是绑定的事件、附加的数据等都会被移除

$('#box').click(function () {
      console.log('box')
    })
    $('#p1').click(function () {
      console.log('p1')
    })
    $('#box').data('id','11');
    apple = $("#box");
    $("#box").remove();
    console.log($("#box"));//jQuery对象中还存在
    console.log($("#box").data('id'));//null,data被清空
    $('body').append(apple);//apple中的事件和data都是undefined
    console.log($("#box").data('id'));//undefined

detach():法移除被选元素,包括所有文本和子节点,会保留所有绑定的事件、附加的数据

$('#box').click(function () {
      console.log('box')
    })
    $('#p1').click(function () {
      console.log('p1')
    })
    $('#box').data('id','11');
    apple = $("#box");
    $("#box").detach();
    console.log($("#box"));//jQuery对象中还存在
    console.log($("#box").data('id'));//null,data被清空
    $('body').append(apple);//apple中的data和事件都被保留
    console.log($("#box").data('id'));//11

注:其实remove()和detach()执行后,其实('#box')所代表的DOM 对象都是已经被清空的,但是副本(apple)保存了它的DOM对象信息,真正的区别在于remove()会把其副本(apple)的绑定的事件、附加的数据移除,而detach()没有。当appen之后 ('#box')所代表的DOM 对象都是已经被清空的,但是副本(apple)保存了它的DOM对象信息,真正的区别在于remove()会把其副本(apple)的绑定的事件、附加的数据移除,而detach()没有。当appen之后 (‘#box’)所代表的DOM 对象又被appen所替换

$('#box').click(function () {
      console.log('box')
    })
    $('#p1').click(function () {
      console.log('p1')
    })
    console.log($("#box"));
    $('#box').data('id','11');

    $("#box").detach();
    $("#box").remove();
    console.log($("#box"));//jQuery对象中还存在,但是dom对象没有了
    console.log($("#box").data('id'));//null,data被清空
    $('body').append($("#box"));//页面上没有节点内容
    console.log($("#box").data('id'));//null
    console.log($("#box"))
7.判断一个dom节点是否存在

$(selector) 不论什么情况都会返回JQuery 对象, 所以不能按照以下的方式 判断节点是否存在

if($('#aa')){} //不可以这么写

正确方法1:

if($('#aa').lenght>0){}

正确方法2:

if($('#aa')[0]){}
8.实现checkbox的状态切换(Toggle)
var checkbox = $(this).find(':checkbox');
checkbox.prop('checked', !checkbox.prop('checked'));
9.表格排序
//tr排序
    var rows = $tbody.find('tr');
    rows.sort(function (row1, row2) {
      var val1 = $(row1).data('rank');
      var val2 = $(row2).data('rank');
      if (val1 < val2) {
        return -1;
      } else if (val1 > val2) {
        return 1;
      } else {
        return 0;
      }
    });
    $tbody.append(rows);
10.有时候不希望网页的某一部分内容被选择比如复制粘贴这种事情,我们可以这么做:
$('p.descr').attr('unselectable', 'on').css('user-select', 'none').on('selectstart', false);
11.trigger 模拟触发事件

trigger模拟触发一个click事件

var press = $('#press');
press.on('click',function(e, how){
    how = how || '';
    alert('The buton was clicked ' + how + '!');
});

press.trigger('click');
press.trigger('click',['fast']);

使用on()方法创建自己喜欢的事件名称,然后通过trigger来触发

<button id="button1">Jump</button> <button id="button2">Punch</button> <button id="button3">Click</button> <button id="clear" style="float: right;">Clear</button> <div id="eventDiv"></div>
var button1 = $('#button1'),
    button2 = $('#button2'),
    button3 = $('#button3'),
    clear = $('#clear'),
    div = $('#eventDiv');

div.on({
    jump : function(){
        alert('Jumped!');
    },

    punch : function(e,data){
        alert('Punched '+data+'!');
    },

    click : function(){
        alert('Simulated click!');
    }

});

button1.click(function(){
    div.trigger('jump');
});

button2.click(function(){
    // Pass data along with the event
    div.trigger('punch',['hard']);
});

button3.click(function(){
    div.trigger('click');
});

clear.click(function(){
    //some clear code
});
12.平行的运行多个Ajax请求
$.when($.get('assets/misc/1.json'), $.get('assets/misc/2.json')).then(function(r1, r2){
    console.log(r1[0].message + " " + r2[0].message);
})
13.使用匿名函数来产生一个独立的代码块
(function($){
    var c = 1;
    $.fn.count = function(){
        log(c++);
        return this;
    };  
})(jQuery); 

$(document).count();
$('body').count().count();
14.data获取

建议这么写:

$.data('#id',key,value);
15.$(this)在下边的情况下用this比较方便
$('#someAnchor').click(function() {  alert( this.id );  });
$('#someAnchor').click(function() {alert($(this).attr('id'));});
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值