JQ常用方法(哈哈)

1ajax请求

$(function(){
   $("#send").click(function(){
     $.ajax({
     type:"get",
     async:true, //默认设置为true,所有请求均为异步请求。
      url: "http://www.idaima.com/xxxxx.php",
    data: {
      username: $("#username").val(),
      content: $("#content").val()
     },
     dataType: "json", //xml、html、script、jsonp、text
     beforeSend:function(){},
    complete:function(){},
    success: function(data) {
      alert(data)
   }
     error:function(){},
   })
  })
})

2, 获取checkbox,判断是否选中

$("input[type='checkbox']").is(':checked')
//返回结果:选中=true,未选中=false

3, 获取checkbox选中的值

var chk_value =[];
$('input[name="test"]:checked').each(function(){
chk_value.push($(this).val());
});

each() 方法规定为每个匹配元素规定运行的函数。

语法  $(selector).each(function(index,element))

4,checkbox全选/反选/选择奇数

$("document").ready(function() {
        $("#btn1").click(function() {
              $("[name='checkbox']").attr("checked", 'true'); //全选
         }) $("#btn2").click(function() {
              $("[name='checkbox']").removeAttr("checked"); //取消全选
             }) $("#btn3").click(function() {
             $("[name='checkbox']:even").attr("checked", 'true'); //选中所有奇数
           }) $("#btn4").click(function() {
               $("[name='checkbox']").each(function() { //反选
       if ($(this).attr("checked")) {
       $(this).removeAttr("checked");
        } else {
           $(this).attr("checked", 'true');
         }
      })
   })
})

5,根据索引值设置任意一个radio为选中值:

$('input:radio').eq(索引值).attr('checked', 'true');//索引值=0,1,2....

6、jQuery对象与dom对象的转换 

普通的dom对象一般可以通过$()转换成jquery对象。 $(document.getElementById("msg"))

由于jquery对象本身是一个集合。所以如果jquery对象要转换为dom对象则必须取出其中的某一项,一般可通过索引取出。
如:$("#msg")[0],$("div").eq(1)[0],$("div").get()[1],$("td")[5]

 
神奇的toggle
toggle(evenFn,oddFn): 每次点击时切换要调用的函数。如果点击了一个匹配的元素,则触发指定的第一个函数,当再次点击同一元素时,则触发指定的第二个函数。随后的每次点击都重复对这两个函数的轮番调用。
举个栗子:

//每次点击时轮换添加和删除名为selected的class。
  $("p").toggle(function(){
    $(this).addClass("selected");
   },function(){
    $(this).removeClass("selected");
  });

 
原文地址:https://www.cnblogs.com/bobofuns/p/6808586.html