document.querySelectorAll('input[type="password"]').forEach(function(f) { f.type = "text"; // 将密码输入框的类型改为文本框 });这个程序的另三种写法
时间: 2024-11-22 21:47:28 浏览: 53
这个JavaScript代码片段通过`querySelectorAll`选择所有`type="password"`的输入元素,并遍历它们,将每个输入元素的`type`属性从"password"改为"text",即将其转换为文本框显示内容而不是密码。以下是三种不同的写法:
1. 使用箭头函数:
```javascript
document.querySelectorAll('input[type="password"]').forEach(input => {
input.type = "text";
});
```
2. 使用扩展运算符和Array.prototype.map():
```javascript
document.querySelectorAll('input[type="password"]')
.map(input => (input.type = "text"), []);
```
注意这里第二个参数数组为空,因为`map()`不需要传入额外的回调值。
3. ES6的模板字符串和解构赋值:
```javascript
['input[type="password"]'].forEach(`input${0}.type = "text";`);
```
但这种方法不太常见,因为它直接操作了HTML元素,而实际应用中一般推荐使用更安全的DOM操作方式。
相关问题
document.querySelectorAll(‘input[type=“password”]’).forEach(function(f) { f.type = “text”; // 将密码输入框的类型改为文本框 });这个程序的另五种写法
这个JavaScript代码片段使用了querySelectorAll方法获取页面上所有type属性为"password"的`<input>`元素,并对它们的type属性进行了修改,将其从"password"更改为"text"。以下是另外五种实现同样功能的不同写法:
1. 使用ES6的Array.from()和map()方法:
```javascript
let passwordInputs = Array.from(document.querySelectorAll('input[type="password"]'));
passwordInputs.map(input => input.type = 'text');
```
2. 利用ES5的for...of循环:
```javascript
for (let f of document.querySelectorAll('input[type="password"]')) {
f.type = "text";
}
```
3. 使用`.forEach()`配合箭头函数:
```javascript
document.querySelectorAll('input[type="password"]').forEach(input => input.type = 'text');
```
4. 利用现代浏览器支持的HTMLCollection遍历:
```javascript
let inputs = document.getElementsByTagName('input');
inputs.filter(input => input.getAttribute('type') === 'password').forEach(input => input.type = 'text');
```
5. 如果需要封装成一个自定义函数,可以这样写:
```javascript
function changeInputType(typeToChange) {
document.querySelectorAll(`input[type="${typeToChange}"]`).forEach(input => input.type = 'text');
}
changeInputType('password');
```
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>主页</title> <link rel="stylesheet" type="text/css" href="css/bootstrap.min.css"> </head> <body> <div class="container"> <h1 class="text-dark-emphasis text-center mt-5">学生管理系统</h1> <form method="post" action="" class="row g-3 mt-3 d-flex justify-content-around align-items-center"> <div class="col-auto"> <label for="name" class="text-primary-emphasis">姓名</label> </div> <div class="col-auto"> <input type="text" class="form-control" id="name" placeholder="请输入姓名"> </div> <div class="col-auto"> <label for="age" class="text-primary-emphasis">年龄</label> </div> <div class="col-auto"> <input type="number" class="form-control" id="age" placeholder="请输入年龄"> </div> <div class="col-auto"> <label for="address" class="text-primary-emphasis">地址</label> </div> <div class="col-auto"> <input type="text" class="form-control" id="address" placeholder="请输入地址"> </div> <div class="col-auto"> <button type="submit" class="btn btn-dark">保存</button> </div> </form> <table class="mt-3 table table-light table-bordered text-center"> <thead> <tr class="text-primary-emphasis"> <th scope="col">学号</th> <th scope="col">姓名</th> <th scope="col">年龄</th> <th scope="col">地址</th> <th scope="col">操作</th> </tr> </thead> <tbody> <tr> <th scope="row">1</th> <td>张三</td> <td>15岁</td> <td>江西省南昌市青山湖区北京东路58号</td> <td> <button type="button" class="btn btn-sm btn-secondary mx-3" onclick="fillForm(this)">修改</button> <button type="button" class="btn btn-sm btn-danger">删除</button> </td> </tr> <tr> <th scope="row">2</th> <td>李四</td> <td>18岁</td> <td>江西省南昌市青山湖区北京东路59号</td> <td> <button type="button" class="btn btn-sm btn-secondary mx-3" onclick="fillForm(this)">修改</button> <button type="button" class="btn btn-sm btn-danger">删除</button> </td> </tr> </tbody> </table> </div> <script> let name = document.getElementById('name') let age = document.getElementById('age') let address = document.getElementById('address') function fillForm(item) { const tr = item.parentNode.parentNode let nodes = tr.querySelectorAll('td') console.log(nodes) name.value = nodes[0].innerText age.value = parseInt(nodes[1].innerText) address.value = nodes[2].innerText } </script> </body> </html><!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <link rel="stylesheet" type="text/css" href="css/bootstrap.min.css"> <title>登录页</title> <style> form { margin: 200px auto; width: 35%; height: 25%; } div.card { padding-left: 50px; padding-right: 50px; } </style> </head> <body> <div class="container"> <form class="text-center"> <img class="mb-4" src="img/logo.svg" alt="Logo" width="120" height="120"> <h1 class="h3 mb-4 fw-normal">登录</h1> <div class="mb-4 form-floating"> <label for="username">用户</label> <input type="text" class="form-control" id="username"> </div> <div class="mb-4 form-floating"> <label for="password">密码</label> <input type="password" class="form-control" id="password"> </div> <button class="w-100 btn btn-lg btn-dark" type="submit">登录</button> <p class="mt-5 mb-3 text-muted">© 2025–2035</p> </form> </div> </body> </html>
你的代码已经很好地完成了学生管理系统的前端界面和登录页的布局,但目前还缺少以下几个关键功能:
1. **表单提交逻辑未实现**:点击“保存”按钮后,没有将输入的数据添加到表格中。
2. **删除功能未实现**:点击“删除”按钮无法移除对应的学生记录。
3. **修改功能不完整**:虽然有 `fillForm` 函数,但它只填充了表单字段,并没有切换为“更新”状态(比如显示一个“更新”按钮)。
4. **数据持久化缺失**:页面刷新后所有数据都会丢失。
5. **登录页无跳转或验证逻辑**。
---
### ✅ 下面我将为你补充这些功能,使系统具备基本的增删改查能力(CRUD),使用纯 HTML + JavaScript 实现。
---
## 1. 增加学生信息并展示在表格中
我们将为“保存”按钮添加事件处理函数,收集输入框内容并动态添加到表格中。
```html
<script>
let name = document.getElementById('name')
let age = document.getElementById('age')
let address = document.getElementById('address')
// 用于存储当前正在编辑的学生索引
let editIndex = -1;
function fillForm(item) {
const tr = item.parentNode.parentNode;
let nodes = tr.querySelectorAll('td');
name.value = nodes[0].innerText;
age.value = parseInt(nodes[1].innerText);
address.value = nodes[2].innerText;
editIndex = parseInt(tr.children[0].innerText) - 1; // 获取学号并转换为索引
}
function saveStudent() {
if (!name.value || !age.value || !address.value) {
alert("请填写所有字段!");
return;
}
const tbody = document.querySelector("tbody");
if (editIndex >= 0) {
// 更新已有行
const row = tbody.rows[editIndex];
row.cells[0].innerText = name.value;
row.cells[1].innerText = age.value + "岁";
row.cells[2].innerText = address.value;
editIndex = -1;
} else {
// 添加新行
const newRow = tbody.insertRow();
newRow.innerHTML = `
<th scope="row">${tbody.rows.length + 1}</th>
<td>${name.value}</td>
<td>${age.value}岁</td>
<td>${address.value}</td>
<td>
<button type="button" class="btn btn-sm btn-secondary mx-3" onclick="fillForm(this)">修改</button>
<button type="button" class="btn btn-sm btn-danger" onclick="deleteStudent(this)">删除</button>
</td>
`;
}
// 清空表单
name.value = "";
age.value = "";
address.value = "";
}
function deleteStudent(button) {
const row = button.parentNode.parentNode;
row.remove();
// 重新编号学号
const rows = document.querySelectorAll("tbody tr");
rows.forEach((tr, index) => {
tr.querySelector("th").innerText = index + 1;
});
}
</script>
```
> 将上述 `<script>` 替换掉你原来的 `<script>` 标签中的内容即可。
---
## 2. 给“保存”按钮绑定事件
在 `<form>` 中加入 `onsubmit="event.preventDefault(); saveStudent()"`,防止默认提交行为并调用我们定义的方法。
```html
<form method="post" action="" class="row g-3 mt-3 d-flex justify-content-around align-items-center"
onsubmit="event.preventDefault(); saveStudent()">
```
---
## 3. 登录页添加简单验证跳转逻辑
在登录页底部添加如下脚本,模拟登录验证并跳转主页。
```html
<script>
document.querySelector("form").addEventListener("submit", function(e) {
e.preventDefault();
const username = document.getElementById("username").value;
const password = document.getElementById("password").value;
if (username === "admin" && password === "123456") {
window.location.href = "index.html"; // 假设主页是 index.html
} else {
alert("用户名或密码错误");
}
});
</script>
```
---
## ✅ 最终效果说明
- 表单输入后点击“保存”,会新增一行学生数据。
- 点击“修改”按钮会自动回填数据,再次点击“保存”即可更新。
- 点击“删除”按钮可以删除该行数据。
- 登录页简单判断用户名密码是否为 admin/123456,正确则跳转主页。
---
## ❗注意事项
- 当前数据没有持久化,页面刷新数据会丢失。如果需要长期保存,需结合本地存储(localStorage)或后端接口。
- 可以进一步优化 UI 和交互体验,例如添加提示框、加载动画等。
---
##
阅读全文
相关推荐
















