[英]How to append an object to an empty object
我在一个表格中有多个问题,我正在尝试 append 每个回答一个空的 object:
const y = document.createElement("INPUT");
y.setAttribute("class", "textBox");
y.setAttribute("id", "fourthQID");
window.data.appendChild(y);
for (const o of i.options){
const x = document.createElement("INPUT");
x.setAttribute("type", "radio");
x.setAttribute("id", "radioID");
x.name = "RadioBtn";
x.value = o;
const y = document.createElement("LABEL");
const t = document.createTextNode(o);
y.appendChild(t);
const div = document.createElement("div");
div.style.height = "5px";
div.appendChild(x);
div.appendChild(y);
document.getElementById("radioButton").appendChild(div);
window.data.appendChild(x);
window.data.appendChild(y);
window.data.appendChild(div);
}
const answers = [];
const data = {"answers": []};
const fourthQuestion = JSON.stringify(document.getElementById('fourthQID').value);
const fifthQuestion = JSON.stringify(document.querySelector("input[name=RadioBtn]:checked").value);
我已经尝试过了,但它似乎不起作用:
answers.push(firstQuestion);
answers.push(secondQuestion);
data.answers.push(firstQuestion);
data.answers.push(secondQuestion);
如何在answers = []
中以 JSON 形式从表格中获得答案?
对 append 每个回答一个空的 object 尝试 Object.assign()。
// The Object.assign() method copies all enumerable own properties from one or more source objects to a target object. It returns the target object.
const returnedTarget = Object.assign(target, source);
更好的解决方案是使用 FormData()。 例如:
// get form values
const myForm = document.forms.FORM_NAME_ATTRIBUTE;
// init new FormData() object
const formData = new FormData();
// Add form elements to formData object
[...myForm.elements].forEach((element) => {
if (element.name.length > 0) {
formData.append(element.name, element.value);
}
});
// or use formData.append() to add elements
formData.append(el.name, el.value);
// and then stringify FormData
var object = {};
formData.forEach(function(value, key){
object[key] = value;
});
var json = JSON.stringify(object);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.