如何确认checkbox是否被选中和改变checkbox的选中状态
$(this).is(':checked'); //true false
$(this).attr("checked",true) //选中
$(this).attr("checked",false) //未选中
//这两个是有区别的
$(this).prop("checked",true)
$(this).prop("checked",false)
原来,在jquery里,有两种操作元素属性的方法,一种是attr(),另一种是prop().
attr()是用来改变元素的attributes属性的,而prop()方法是用来改变元素properties属性的,那么这两者有何区别呢。
在默认情况下,attributes和properties是一样的,都是用来保存元素的属性值的。
但是,当涉及到boolean值时,比如checkbox这样的,有true和false这样的布尔值的元素属性,attributes在页面加载的时候就被设置,并且一直保持初始值,而properties则存储着元素属性的当前值。
也就是说:boolean properties保持最新。但相应的boolean attributes是不一样的,正如上面所述,它们仅被浏览器用来保存初始值
所以,涉及到boolean properties要在页面加载后随时更新的话,那还是要使用prop()方法。
反选代码
//反选
$("#unchecked").click(function(){
$("input[type='checkbox']:lt(5)").each(function(){
if($(this).is(':checked')) {
$(this).prop("checked",false);
}else{
$(this).prop("checked",true);
}
})
})
全选或者全不选
$("#qx").click(function(event) {
var xx=$(this).is(':checked');
if(xx==true){
$("input[type='checkbox']").each(function(){
$(this).prop("checked",true)
})
}else{
$("input[type='checkbox']").each(function(){
$(this).prop("checked",false)
})
}
});
由jquery动态生成的标签绑定不了事件的问题
//这是由jquery动态生成的td,无法绑定事件
$("td").click(function(event) {
alert()
});
//可以换成这种形式
$(document).on("click",'td',function(event){
alert()
})
关于js中字符串的小问题
获取字符串中最后一个字符的位置
var s="7ss7hnj765";
s=s.lastIndexOf("j")
alert(s)
截取字符串
方法:substring() 方法 string.substring(from, to) 方法从 from 位置截取到 to 位置,to 可选,没有设置时默认到末尾
var str="www.runoob.com!";
document.write(str.substring()+"<br>"); // 从第 5 个字符开始截取到末尾
document.write(str.substring(,)); // 从第 5 个字符开始截取到第10个字符
方法:substr() 方法
substr() 方法可在字符串中截取从开始下标开始的指定数目的字符。
var str="www.runoob.com!";
document.write(str.substr(,)); // 从第 4 个字符开始截取6个字符
下面提一下jQuery的each方法的几种常用的用法
Js代码
var arr = [ “one”, “two”, “three”, “four”];
$.each(arr, function(){
alert(this);
});
//上面这个each输出的结果分别为:one,two,three,four
var arr1 = [[, , ], [, , ], [, , ]]
$.each(arr1, function(i, item){
alert(item[]);
});
//其实arr1为一个二维数组,item相当于取每一个一维数组,
//item[0]相对于取每一个一维数组里的第一个值
//所以上面这个each输出分别为:1 4 7
var obj = { one:, two:, three:, four:};
$.each(obj, function(key, val) {
alert(obj[key]);
});
//这个each就有更厉害了,能循环每一个属性
//输出结果为:1 2 3 4