每次在使用前都要引入jquery库
<script src="lib/jquery-3.2.1.js"></script>
jquery语法
获取元素
JS:document.getElementById(); JQ:$(“#id”);
Jquery对象与DOM对象转换
例如:向页面<span></span>标签的元素添加/修改信息
<script>//js方式实现function JSWrite(){//document.getElementById("span1").innerHTML="美美哒!";var spanEle = document.getElementById("span1");//DOM对象转换成JQ对象的第一种方式$(spanEle).html("美美哒!");}//JQ方法实现$(function(){document.getElementById("btn1").onclick = function(){document.getElementById("span1").innerHTML="帅帅哒!";}$("#btn1").click(function(){//JQ对象转换成DOM对象的第一种方式//$("#span1")[0].innerHTML="呵呵哒!";//JQ对象转换成DOM对象的第二种方式$("#span1").get(0).innerHTML="呵呵哒!";});});</script>
<div id="app">hello world</div><script>let app = $("#app");// jquery方法app.click(function(){$(this).css({color:"red"})})//原生js方法var p = document.getElementById("app")p.onclick=function(){this.style.color="red"}</script>
选择器
<body><div style="background-color: salmon;" id="div1"></div><hr><div style="background-color: salmon;" id="div2"></div><hr><div style="background-color: salmon;"></div><hr><div style="background-color: salmon;"></div><hr><div style="background-color: salmon;"></div><hr><div style="background-color: salmon;"></div><hr><div style="background-color: salmon;"></div><hr><div style="background-color: salmon;"></div><hr><script src = "../jquery.js"></script><script>$("#div1,#div2").height(150).width(150); //可以放多个选择器</script>
案例
案例1:使用JQ完成表格的隔行换色
<script type="text/javascript" src="../js/jquery-1.8.3.js" ></script><link rel="stylesheet" type="text/css" href="../css/style.css"/><script>$(function(){//CSS文件中配置好even和odd两个class类$("tbody tr:even").addClass("even");$("tbody tr:odd").addClass("odd");});</script>
案例2:使用JQ完成全选和全不选
<script type="text/javascript" src="../js/jquery-1.8.3.js" ></script><script>$(function(){//找到下面所有的复选框并设置属性checked()/*if($("#select")[0].checked==true){$(".selectOne").attr("checked",true)}*/$("#select").click(function(){//$(".selectOne").attr("checked",this.checked);//注意:attr在jquery1.11版本不适用,采用prop()来替代(在各个版本都适用)。$(".selectOne").prop("checked",this.checked);});});</script>
