我在表单元素中动态生成输入字段。
现在,对于在每个 Enter 按键事件上创建的每个新输入元素,我想使用 setAttribute() 方法设置一个新的“name”属性。但我想动态地将值分配给 name 属性,而不是对其进行硬编码。对于前。
newelement.setAttribute("name", a_new_generated_value)
。
我怎样才能实现这个目标?
预先感谢您的帮助。
我试过这个:
function newitem() {
var checkbox = document.createElement("input");
checkbox.setAttribute("type", "checkbox");
checkbox.setAttribute("name", "checkbox" + newtaskcount);
var newtask = document.createElement("input");
newtask.setAttribute("type", "text");
newtask.setAttribute("name", "task" + newtaskcount);
return { checkbox, newtask };
}
在上面的回调函数中,“newtaskcount”是在其他函数中生成的。
我期待以下物体: 新任务1 { "checkbox1" : "选中"; “任务1”:“abc” }
新任务2 { "checkbox2" : "选中"; “任务2”:“xyz” }
等等..
您是对的,但您需要创建元素并使用
newtaskcount
变量动态命名它们
像这样
function newitem() {
var newtaskcount = /* generate newtaskcount */;
var checkbox = document.createElement("input");
checkbox.setAttribute("type", "checkbox");
checkbox.setAttribute("name", "checkbox" + newtaskcount);
checkbox.checked = true; // Set the checkbox as checked
var newtask = document.createElement("input");
newtask.setAttribute("type", "text");
newtask.setAttribute("name", "task" + newtaskcount);
newtask.value = /* set the value for newtask */;
return { checkbox, newtask };
}
您必须将
/* generate newtaskcount */
和 /* set the value for newtask */
替换为生成 newtaskcount
并设置 newtask
值的实际逻辑。此代码将创建一个新复选框。
谢谢