1、使用原生JS
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script>
function switchUser() {
let 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>
2、使用jquery
使用$("#id").attr("readonly","true")添加readonly属性
使用$("#id").attr("readonly","false")设置readonly属性失效,但是不管用啊........
最后使用$("#id").removeAttr("readonly")移除该属性后成功