<div class="test bac sss"></div>
<!--<div>1111</div>-->
<input type="checkbox" checked="checked" name="" id="" value="" />
<input type="text" name="" id="" value="1234" />
<input type="text" name="" id="" value="666" />
属性
获取/设置元素属性
1、attr(property,val),prop(property,val)
property:表示的是属性名
val:可选,当设置了val值时,表示用来设置该属性
attr获取到的属性是写死在html结构上的值,不会随着复选框的状态改变而改变
prop获取到的属性值是动态的,可以随着复选框的状态改变而改变
原生获取动态的复选框状态值,可以用原生对象加checked
比如:var inp = inp.checked;
2、removeAttr(property);移除元素属性
property:表示需要移除的属性
3、val()获取表单元素值
//$("input[type=checkbox]").removeAttr("checked","");
$("input[type=checkbox]").attr("checked",false);
console.log($("input[type=checkbox]").prop("checked"));
$("input[type=checkbox]").change(function(){
var inp= $("input[type=checkbox]").attr("checked");
var inp1 = $("input[type=checkbox]").prop("checked");
console.log(inp,inp1);
});
$("input[type=checkbox]")[0].onchange=function(){
//getAttribute获取到的是一个静态属性
var inp= $("input[type=checkbox]")[0].getAttribute("checked");
console.log(inp);
}
$("input[type=checkbox]")[0].onchange=function(){
var inp= $("input[type=checkbox]")[0].checked;
console.log(inp);
}
var inpt=$("input[type=text]").val();
console.log(inpt);
val(function)用来设置表单元素的值,返回一个jq对象
function:表示回调函数,接收两个参数
第一个值表示下标值
第二个值表示元素的值
var inpt1 = $("input[type=text]").val(function(index,value){
if(index==1){
value = value+1;
}
return index+"+"+value;
})
console.log(inpt1);
$("input[type=text]")[0].value+="aaaaa";
addClass(property/func),添加类名
property:表示需要添加的类名
func:回调函数,接收两个参数
第一个参数为下标值
第二个参数是当前的类名
#切换类名的效果
$("div").on("click",function(){
//$(".test").addClass("chang");
var test = $("div").addClass(function(index,currentClass){
console.log(index,currentClass);
var newClass = currentClass=="test"?"chang":"test";
$("div").removeClass(currentClass);
return newClass;
});
console.log(test);
})
#css()用来设置元素样式
#用法一
//$(".test").css("background","gray");
#用法二
$(".test").css({
"background":"red",
"opacity":"0.8"
});
#用法三
$(".test").css("background",function(){
//方法一
var arr=[1,2,3,4,5,6,7,8,9,"a","b","c","d","e","f"];
var res = "";
for (var i=0;i<6;i++){
var ram = Math.floor(Math.random()*arr.length);
res+=arr[ram];
}
console.log(res)
return "#"+res;
//方法二
var res = "";
for (var i=0;i<6;i++){
var ram = Math.floor(Math.random()*16).toString(16);
res+=ram;
}
console.log(res)
return "#"+res;
})
#用法四
var i=100;
setInterval(function(){
i>300?i-=200:i++;
$(".test").css({
"width":function(){
return i+"px";
},
"height":function(){
return i+"px";
}
})
},1000/60);
hasClass()
检查元素是否具有某个类名
removeClass()移除某些类名
console.log($("div").hasClass("test"));
#以下写法叫:链式写法
$("div").removeClass("test bac sss").addClass("chang");//可以移除多个类名同时添加类名
$("div").removeClass(function(index,classN){
console.log(index,classN);
return classN;
}).addClass("test");
/**
* toggleClass()切换类名
*
* **/
/* $("div").on("click",function(){
$("div").toggleClass("chang");
})*/
$("div").on("click",function(){
$("div").toggleClass(function(){
return "chang"
});
});