要判断数组中是否包含某个元素
var arr = [ "xml", "html", "css", "js" ]; $.inArray("js", arr); //返回 3,
//全选 $("input[name='checkbox']").attr("checked","true"); //取消全选 $("input[name='checkbox']").removeAttr("checked"); //选中所有基数 $("input[name='checkbox']:even").attr("checked","true"); //选中所有偶数 $("input[name='checkbox']:odd").attr("checked","true"); //反选 $("input[name='checkbox']").each(function(){ if($(this).attr("checked")) {$(this).removeAttr("checked");} else {$(this).attr("checked","true");} //获取选择项的值 $("input[name='checkbox']:checkbox:checked").each(function(){ aa+=$(this).val() }) document.write(aa);
//循环读取checkbox值 $("input[type=checkbox][checked]").each(function(){ //由于复选框一般选中的是多个,所以可以循环输出 alert($(this).val()); });
==================================================================================
prop 和 attr 的使用区别
在高版本的jquery引入prop方法后,什么时候该用prop?什么时候用attr?它们两个之间有什么区别?这些问题就出现了。
关于它们两个的区别,简单总结下:
对于HTML元素本身就带有的固有属性,在处理时,使用prop方法
对于HTML元素我们自己自定义的DOM属性,在处理时,使用attr方法。
<input id="chk1" type="checkbox" />是否可见 <input id="chk2" type="checkbox" checked="checked" my-attr="myAttr" />是否可见
像checkbox,radio和select这样的元素,选中属性对应“checked”和“selected”,这些也属于固有属性,因此需要使用prop方法去操作才能获得正确的结果,my-attr是我自己定义的;咱们使用attr();
$("#chk1").prop("checked") == false $("#chk2").prop("checked") == true $("#chk1").attr("checked") == undefined $("#chk2").attr("checked") == "checked"
==========================================================================================
//注意: 操作checkbox的checked,disabled属性时jquery1.6以前版本用attr,1.6以上(包含)建议用prop //1、根据id获取checkbox $("#cbCheckbox1"); //2、获取所有的checkbox $("input[type='checkbox']");//or $("input[name='cb']"); //3、获取所有选中的checkbox $("input:checkbox:checked");//or $("input:[type='checkbox']:checked");//or $("input[type='checkbox']:checked");//or $("input:[name='ck']:checked"); //4、获取checkbox值 //用.val()即可,比如: $("#cbCheckbox1").val(); //5、获取多个选中的checkbox值 var vals = []; $('input:checkbox:checked').each(function (index, item) { vals.push($(this).val()); }); //6、判断checkbox是否选中(jquery 1.6以前版本 用 $(this).attr("checked")) $("#cbCheckbox1").click(function () { if ($(this).prop("checked")) { alert("选中"); } else { alert("没有选中"); } }); //7、设置checkbox为选中状态 $('input:checkbox').attr("checked", 'checked');//or $('input:checkbox').attr("checked", true); //8、设置checkbox为不选中状态 $('input:checkbox').attr("checked", '');//or $('input:checkbox').attr("checked", false); //9、设置checkbox为禁用状态(jquery<1.6用attr,jquery>=1.6建议用prop) $("input[type='checkbox']").attr("disabled", "disabled");//or $("input[type='checkbox']").attr("disabled", true);//or $("input[type='checkbox']").prop("disabled", true);//or $("input[type='checkbox']").prop("disabled", "disabled"); //10、设置checkbox为启用状态(jquery<1.6用attr,jquery>=1.6建议用prop) $("input[type='checkbox']").removeAttr("disabled");//or $("input[type='checkbox']").attr("disabled", false);//or $("input[type='checkbox']").prop("disabled", "");//or $("input[type='checkbox']").prop("disabled", false);