工具方法:
- 1.attr():获取某个标签属性的值,或设置某个标签属性的值
- 2.removeAttr():删除某个标签属性
- 3.addClass():给某个标签添加class属性值
- 4.removeClass():删除某个标签class属性值
- 5.prop():和attr()类似,区别在于prop用于属性值为Boolean类型的情况,比如多选
案例:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>课堂案例</title> <script src="js/jquery-3.6.4.js"></script> <style> .add{ background-color: antiquewhite; } .add2{ background-color: aquamarine; } #choice1,#choice2{ width: 30px; height: 20px; } </style> <script type="text/javascript"> $(function(){ $("#img").click(function(){ //attr()的使用:获取某个标签属性的值,或设置某个标签属性的值 会覆盖class值 // $("div").attr("class","add2") $("img").attr("src","img/bg3.jpg") //removeAttr()的使用:删除某个标签属性 $("img").removeAttr("alt") //addClass()的使用:给某个标签添加class值 不会覆盖class值 // $("div").addClass("add2") //removeClass的使用:删除某个标签class属性值 $("div").removeClass("add") //prop()适用于表单操作 与attr()类似 用于Boolean值类型的属性 $("#inputs").prop("checked","true") }) //鼠标移入改变颜色 $("#YU tr td").mouseover(function(){ console.log(this) $(this).css("background","red") }).mouseout(function(){ $(this).css("background","beige") }) //全选与全不选案例 $("#choice1").click(function(){ if($(this)[0].checked){ $(".chocie").prop("checked",true) }else{ $(".chocie").prop("checked",false) } }) $(".chocie").click(function(){ console.log($("input[type='checkbox']")) if($(" input[class='chocie']").length==$("input[class='chocie']:checked").length){ $("#choice1").prop("checked",true) }else{ $("#choice1").prop("checked",false) } }) }) </script> </head> <body> <button id="img">切换</button> <div class="add"> <img src="img/bg1.jpg" alt="" style="width: 500px; height: 300px;"> </div> <input type="checkbox" value="湖南省" id="inputs">湖南省 <input type="checkbox" value="湖北省">湖北省 <!-- 隔行更换颜色 --> <table id="YU" style="width: 100%;" border="1"> <tr> <td> </td> <td> </td> <td> </td> <td> </td> </tr> <tr> <td> </td> <td> </td> <td> </td> <td> </td> </tr> <tr> <td> </td> <td> </td> <td> </td> <td> </td> </tr> <tr> <td> </td> <td> </td> <td> </td> <td> </td> </tr> </table> 全选<input type="checkbox" value="" id="choice1"> <br> <input class="chocie" type="checkbox" value=""> <input class="chocie" type="checkbox" value=""> <input class="chocie" type="checkbox" value=""> <input class="chocie" type="checkbox" value=""> </body> </html>
以上是详细案例的全部代码,新增jQuery鼠标移入改变颜色事件及全选框,全不选框事件,供学习参考