attr和prop区别
css()操作的是标签的宽、高、背景色、display、font-size,font-weight等
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> <style> div{ width: 200px; height: 200px; background-color: red; } </style> </head> <body> <div id="box" class="active"></div> <button>按钮</button> </body> <script type="text/javascript" src="../../js/jquery-1.10.1.js" ></script> <script> $("button").click(function(){ $("div").css({ "width":100, "height":100, background: "blue" }) }) </script> </html>
=====================================
attr:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> <style> div{ width: 200px; height: 200px; background-color: red; } </style> </head> <body> <div id="box" class="active"></div> <button>按钮</button> </body> <script type="text/javascript" src="../../js/jquery-1.10.1.js" ></script> <script> $("button").click(function(){ var box1 = $("div").attr("id"); console.log(box1); var class1 = $("div").attr("class"); console.log(class1); }) </script> </html>
=============================================
prop:
复选框:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> </head> <body> <input type="checkbox" value="1" name="hobby" /> 篮球 <input type="checkbox" value="2" name="hobby" /> 排球 <input type="checkbox" value="3" name="hobby" /> 敲代码 <input type="checkbox" value="4" name="hobby" /> 看看书 <br> <br> <br> <button>全选</button> <button>全不选</button> </body> <script type="text/javascript" src="../../js/jquery-1.10.1.js" ></script> <script> $("button:eq(0)").click(function(){ $("input:checkbox").prop("checked",true); }) $("button").eq(1).on('click',function(){ $(":checkbox").prop("checked",false); }) </script> </html>
单选框:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> </head> <body> <input type="radio" name="sex" checked value="0"> 男 <input type="radio" name="sex" value="1"> 女 <input type="radio" name="sex" value="2"> 保密 </body> <script type="text/javascript" src="../../js/jquery-1.10.1.js" ></script> <script> // 目前默认选中的是男 // 假设后台传递给前台的数据value=1,也就是女被选中 $(function(){ $("input").each(function(index,ele){ var value = $(this).val(); if(value === "1"){ $(this).prop("checked",true); } }) }) </script> </html>
下拉框:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> </head> <body> <select name="provice"> <option value="">请选择</option> <option value="1">陕西</option> <option value="2">山西</option> <option value="3">广东</option> <option value="4">广西</option> </select> </body> <script type="text/javascript" src="../../js/jquery-1.10.1.js" ></script> <script> // 目前默认选中的是请选择 // 假设后台传递给前台的数据value=1,也就是陕西需要被选中 $(function(){ // 虚拟的数字,相当于后台传递给前台 var province = "1"; $("option").each(function(index,ele){ var value = $(this).val(); if(value === province){ $(this).prop("selected",true); } }) }) </script> </html>
attr:操作属性值为非布尔值的属性
prop:操作属性值为布尔值的属性(selected、checked)

浙公网安备 33010602011771号