一.input標簽
-
-
input標簽的屬性:
-
disabled:表單項禁用,不可修改值,也不會被提交
-
readonly:表單項只讀,不可修改值,但會被提交
二.案例
根據Name來獲取並設計(本人使用)
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> </head> <body> <!--顯示獲取的1值 並且 設置input權限為只讀--> <input type="button" value="只讀/可寫" onclick="autoGain()"> <!--作用框,用於實現效果--> <input type="text" name="wzwName" readonly="readonly"> </body> <script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"> </script> <script type="text/javascript"> // 只讀/可寫 切換單機事件方法 function autoGain() { // 獲取input中的值 var val = $("input[name='wzwName']").val(); // 如果等於1說明已經設置為只讀模式了 if(val == 1) { // 將只讀模式刪除 $("input[name='wzwName']").removeAttr("readonly"); }else{ // 添加只讀模式到input框中並設置value值為1 $("input[name='wzwName']").val("1").attr("readonly","readonly"); } } </script> </html>
根據id來獲取並設計
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script> function switchUser() { var usernameEl = document.getElementById("username"); const beforeVal = usernameEl.getAttribute("readonly"); console.log("切換前狀態:" + getStatus(beforeVal)); if (beforeVal === null) { usernameEl.setAttribute("readonly", "readonly"); } else { usernameEl.removeAttribute("readonly"); } const afterVal = usernameEl.getAttribute("readonly"); console.log("切換后狀態:" + getStatus(afterVal)); } function getStatus(readonlyVal) { if (readonlyVal === null) { return "讀寫" } else { return "只讀" } } </script> </head> <body> 用戶名:<input type="text" id="username" name="username"><br> <button onclick="switchUser()">切換用戶名readonly屬性</button> </body> </html>
三.總結
- 此方法不一定適用於所有人,所有環境,這是我找了5種以上的方法才寫出來的,可能在他人的電腦不一定奏效
- readonly后面的值最好也是要readonly,當然用true也可以,不過調成false可是不會取出只讀的效果
- removeAttr()同樣是找了很久才找到的刪除input標簽上屬性的一種方案,應用范圍很廣!!!
- 我這里只用了以Name為點來寫,可以變化思維,ID同樣奏效