以下是一个示例代码,它遍历一个数组,并将选定的元素复制到HTML表单中:
HTML代码:
Copy Array Elements to Form
JavaScript代码(script.js):
// 假设我们有一个数组
const myArray = ["元素1", "元素2", "元素3", "元素4", "元素5"];
// 获取表单元素
const selectElement = document.getElementById("selectedElement");
// 遍历数组
myArray.forEach((element) => {
// 创建一个选项元素
const option = document.createElement("option");
// 设置选项值为数组元素的值
option.value = element;
// 设置选项文本为数组元素的值
option.text = element;
// 将选项添加到select元素中
selectElement.appendChild(option);
});
这段代码首先获取了HTML表单中的select元素,然后遍历数组myArray。对于每个数组元素,它创建一个option元素,并将其值和文本设置为数组元素的值。最后,它将选项添加到select元素中。这样,就将数组元素复制到了HTML表单中的下拉菜单选项中。