注意:
jquery可以进行隐式迭代 操作一堆
以该页面为例:
<button class="btn">按钮1</button>
<button class="btn">按钮2</button>
<button class="btn">按钮3</button>
<button class="btn">按钮4</button>
<input id="wdnmd" type="text" value="123"/>
<input type="checkbox" checked/> 篮球
<input type="checkbox" checked/> 乒乓球
<input type="checkbox"/> 足球
<input type="checkbox" checked/> 棒球
<input type="checkbox"/> 羽毛球
<div style="height: 1000px"></div>
<div id="block"></div>
<div id="block1"></div>
设置元素的文本
在JS中为:
innerHTML innerText
在jQuery要使用html()或者text(),效果与JS一致,text不会识别标签;
$("button.btn").text("<span>wdnmd</span>");
for (var i = 0; i < $("button.btn").length; i++) {
console.log($("button.btn").eq(i).html());
}
获取或设置元素值 val()
$("#wdnmd").val("32klklkl1");设置元素值
console.log($("input").val());获取
元素类的操作
//给元素添加类 addClass
$("input").addClass("txt txt1");
//给元素移除类名称 removeClass
$("input").removeClass("txt1");
//类别的切换 toggleClass 有则删没有则加
$("input").toggleClass("txt");
//设置属性的方法 attr 参数1 名称 参数2 值 设置或者获取
$("input").attr("id", "user");
console.log($("input").attr("id"));
$("input").attr("data-user", "maodou");
console.log($("input").attr("data-user"));
//移除属性
$("input").removeAttr("id");
$("input").removeAttr("data-user");
$("input").removeAttr("class");
//给元素 一次性设置多个属性
$("input").attr({
id: "username",
"data-list": "list"
});
//prop 设置属性 获取
console.log($("input[type=checkbox]").prop("checked"));
//$("input[type=checkbox]").prop("checked", true);
$("input[type=checkbox]").prop("checked", function (index, value) {
console.log(index);
return !value;
});
$("input[type=checkbox]").prop("id", "checked");
$("input[type=checkbox]").removeProp("id");
css() 设置或者获取元素的样式 设置一个或者多个
$("#block").css("border","1px solid black");
$("#block").css({
width: "100px",
height: "100px",
border: "1px solid black",
backgroundColor: "red"
});
offest/position:获取当前的相对偏移量 返回值是对象 left top
scrollTop 当前元素 相对滚动条到顶部的距离 (谁有滚动条就谁) y
scrollLeft 当前元素 相对滚动条到左边的距离 (谁有滚动条就谁) x
$("#block").offset()
$("#block").position()
$(window).scrollTop()
$(window).scrollLeft()
height width 带回调函数 在旧高上重新设置
可以直接设置:$(#block).height(20);
也可以通过回调函数:
$("#block,#block1").height(function (index, oldheight) {
console.log(oldheight,index);
return oldheight + (index + 1) * 100;
if(index==0){
return oldheight + 100;
}
else{
return oldheight + 200;
}
});
innerheight innerwidth
获取第一个匹配元素内部区域高度或宽度(包括补白、不包括边框)。
此方法对可见和隐藏元素均有效。
jquery选择器:
通过CSS1,CSS3选择器来匹配元素;
这里获取的DOM对象都是集合型
按钮
按钮
- 1
- 2
- 3
- 4
- 5
- 6
<input type=“radio” name=“dad"checked/>篮球
zu球