JavaWEB-jQuary框架基础

jQuary框架

选择器

标签操作

<p id="p1"></p>
$("#p1") //通过给定的id匹配元素

<p class="c1"></p>
$(".c1") //通过给定的css类名匹配元素

$("*") //*表示选择所有
$("#p1,.c1") //","表示选择多个标签

层级关系

祖先后代选择器

$("div p") //匹配div标签下的p标签

父子选择器

$("div>p")

“兄弟”选择器

$("lable+input")//平级关系,找的是lable之后的第一个input

筛选器

$("td:first") //last
$("td:eq(n)") //找第n个
$("td:odd") //下标为奇数的元素(下标0开始) //even下标为偶数的元素
$("td:gt(n)")//下标大于n的元素 //lt 小于
$("td:not(td:gt(n))")取反

属性选择器

$("input[name]"); //选中有name属性的标签
$("input[value=lol]"); //匹配value值为lol的标签
$("input[value^=l]"); //value值以l开头的标签
$("input[type=button][name=aaa]")同时匹配多个属性type是button且name是aaa
$("td:nth-child(n)");//用于选择表格的第几列
$("td:nth-child(1)");表格第一列 nth换成first(第一个)同理last

表单选择器

<input type="button">

$(":button");//找到所有button
$("tbody1 :checkbox:checked"); //找到tbody1中被勾选的复选框

标签操作

修改内容

.text();//获取标签内容,功能等价于:innerText;不带参数是获取
.text(新内容);//修改内容为新的内容

$("p.first").text(); //获取标签内容
$("p.first").text("hehehehe");//替换标签内容
.html();//获取, 功能等价innerHTML
.html("<p>hello</p>");//替换

$("p.first").html(); //获取标签内容
$("p.first").html("<p>helllo</p>");//替换标签内容
.empty(); //清空内容,不删除标签
.remove(); //删除整个标签

$("input:first").remove(); //删除第一个input标签

修改属性

普通属性

.prop("属性名");
.prop("属性名","新值");

$("tbody1 :checkbox").prop("checkbox",true);

特殊属性

文本框的value

.val();
$("input").val();//获取
$("input").val("新值");//修改

样式style //操作标签的样式
.addClass("样式"); //添加样式,推荐使用
.removeClass("样式");
$("p").addClass("a");
$("p").addClass("b");
$("p").addClass("a b");

换样式
$("p:first").css("background-color","red");

显示/隐藏标签

$("p:first").hide();//将标签隐藏,实际上通过样式display:none实现
$("p:first").show();//显示
$("p:first").hide(2000);//花2s隐藏起来(动画效果),同show
$("p:first").toggle();//切换显示,隐藏效果

标签尺寸

.width();
.innerWidth();//宽度=内容+内间距(padding)
.outerWidth();//宽度=内容+内间距(padding)+边框
$("div:first").width(); //div中内容的宽度

.height();同上

$(window) //将原始的window对象包装成了jquary的window对象
$(window).width(); //浏览器页面宽高
$(window).height();

创建标签

$("<input>").prop("type","button").val("按键").appendTo("body");
$("<input type='button' value='按钮'>").appendTo("body");

添加事件

$(选择器).事件方法(匿名函数);

<script>
$("#btn1").click(
    function(){
        console.log("ok");
    }
)
</script> //注意放在body中最后面

要注意整个html的解析顺序,script如果放在head部分,执行时会找不到body中尚未解析的标签

$("#btn1").mouseover(function(){
    //在匿名函数内直接使用this,代表触发样式的标签
    //$(this)把原始对象变为jquery对象,可以调用jquery的方法
    //如果用到事件对象,只需要在匿名函数上添加e
    $(this).addClass("bigger");

});

猜你喜欢

转载自blog.csdn.net/qq_34862798/article/details/82701607