您的位置:首页 > Web前端 > JQuery

jQuery常用方法(持续更新)

2017-04-06 11:33 639 查看

0、常用代码:

请容许我在1之前插入一个0,我觉得我有必要把最常用的代码放在第一位,毕竟大部分时间大家都是找代码的。

(1)AJAX请求

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,并判断是否选中

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

(3) 获取checkbox选中的值

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

(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)获取select下拉框的值

其实下拉框的最简单了,直接val就行了

$("#select").val()

(6)获取选中值,三种方法都可以:

$('input:radio:checked').val();
$("input[type='radio']:checked").val();
$("input[name='rd']:checked").val();

(7)设置第一个Radio为选中值:

$('input:radio:first').attr('checked', 'checked');

或者

$('input:radio:first').attr('checked', 'true');

(8)设置最后一个Radio为选中值:

$('input:radio:last').attr('checked', 'checked');

或者

$('input:radio:last').attr('checked', 'true');

(9)根据索引值设置任意一个radio为选中值:

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

或者

$('input:radio').slice(1,2).attr('checked', 'true');

(10)根据Value值设置Radio为选中值

$("input:radio[value='rd2']").attr('checked','true');

或者

$("input[value='rd2']").attr('checked','true');

1、关于页面元素的引用

通过jquery的$()引用元素包括通过id、class、元素名以及元素的层级关系及dom或者xpath条件等方法,且返回的对象为jquery对象(集合对象),不能直接调用dom定义的方法。http://www.idaima.com/a/1663.html

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

只有jquery对象才能使用jquery定义的方法。注意dom对象和jquery对象是有区别的,调用方法时要注意操作的是dom对象还是jquery对象。

普通的dom对象一般可以通过$()转换成jquery对象。 

如:

$(document.getElementById("msg"))

则为jquery对象,可以使用jquery的方法。

由于jquery对象本身是一个集合。所以如果jquery对象要转换为dom对象则必须取出其中的某一项,一般可通过索引取出。

如:

,$("div").eq(1)[0],$("div").get()[1],$("td")[5]

这些都是dom对象,可以使用dom中的方法,但不能再使用Jquery的方法。 

以下几种写法都是正确的:

$("#msg").html();
$("#msg")[0].innerHTML;
$("#msg").eq(0)[0].innerHTML;
$("#msg").get(0).innerHTML;

3、如何获取jQuery集合的某一项

对于获取的元素集合,获取其中的某一项(通过索引指定)可以使用eq或get(n)方法或者索引号获取,要注意,eq返回的是jquery对象,而get(n)和索引返回的是dom元素对象。对于jquery对象只能使用jquery的方法,而dom对象只能使用dom的方法,如要获取第三个<div>元素的内容。有如下两种方法: 

$("div").eq(2).html(); //调用jquery对象的方法
$("div").get(2).innerHTML; //调用dom的方法属性

4、同一函数实现set和get

Jquery中的很多方法都是如此,主要包括如下几个:
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: