返回

开发中遇到的问题记录(上传、表格错位、input样式、radio相关)

前端





## 上传后不立即提交到后台

在开发过程中,我遇到一个问题是,当我使用 `<input type="file">` 元素上传文件时,文件会被立即提交到后台。然而,我希望在用户点击提交按钮后才将文件提交到后台。

为了解决这个问题,我使用了 `FormData` 对象和 `XMLHttpRequest` 对象。首先,我将 `<input type="file">` 元素的值添加到 `FormData` 对象中。然后,我使用 `XMLHttpRequest` 对象将 `FormData` 对象发送到后台。最后,我使用 `XMLHttpRequest` 对象的 `onload` 事件监听器来处理服务器的响应。

const form = document.getElementById('form');

form.addEventListener('submit', (event) => {
event.preventDefault();

const formData = new FormData();

const fileInput = document.getElementById('file');

formData.append('file', fileInput.files[0]);

const xhr = new XMLHttpRequest();

xhr.open('POST', '/upload');

xhr.onload = () => {
if (xhr.status === 200) {
alert('文件上传成功');
} else {
alert('文件上传失败');
}
};

xhr.send(formData);
});


## 表格错位

在开发过程中,我遇到另一个问题是,当我在表格中添加或删除行时,表格中的其他行会发生错位。

为了解决这个问题,我使用了 `Flexbox` 布局。我将表格设置为 `display: flex;`,并将表格中的每一行设置为 `flex: 1;`。这样,当我在表格中添加或删除行时,表格中的其他行就不会发生错位。

table {
display: flex;
flex-direction: column;
}

tr {
flex: 1;
}


## input为password类型时的样式问题

在开发过程中,我还遇到一个问题是,当我在使用 `<input type="password">` 元素时,输入框的样式很丑。

为了解决这个问题,我使用了 CSS 来修改 `<input type="password">` 元素的样式。我将 `<input type="password">` 元素的 `border` 属性设置为 `none`,并将其 `background-color` 属性设置为 `transparent`。这样,`<input type="password">` 元素的样式就变得更加美观。

input[type="password"] {
border: none;
background-color: transparent;
}


## radio相关的问题

在开发过程中,我还遇到了一些与 `radio` 元素相关的问题。例如,当我使用 `radio` 元素时,我无法选中多个选项。

为了解决这个问题,我使用了 `querySelectorAll()` 方法来获取所有的 `radio` 元素,然后使用 `forEach()` 方法来遍历这些元素,并为每个元素添加一个事件监听器。当用户点击某个 `radio` 元素时,我将该元素的 `checked` 属性设置为 `true`,并将其余 `radio` 元素的 `checked` 属性设置为 `false`。这样,用户就可以选中多个选项。

const radioButtons = document.querySelectorAll('input[type="radio"]');

radioButtons.forEach((radioButton) => {
radioButton.addEventListener('click', (event) => {
radioButtons.forEach((radioButton) => {
radioButton.checked = false;
});

event.target.checked = true;

});
});


## 总结

在开发过程中,我遇到了各种各样的问题。但我通过不断的学习和探索,最终解决了这些问题。我希望这篇文章对其他开发者有所帮助。