gpt4 book ai didi

javascript - 如何在javascript中将输入值设置为对象的属性值

转载 作者:行者123 更新时间:2023-12-03 06:41:59 25 4
gpt4 key购买 nike

我想将输入值设置为对象的属性值,这是 jsfiddle 中的代码,
我也把代码放在这里:
html

<div id="contenu"></div>  

js

// create the button
var contenu = document.getElementById("contenu");
var btn = document.createElement("button");
btn.textContent = "add";
contenu.appendChild(btn);

// click the button to create 2 inputs and submit
btn.addEventListener("click", function(){
// create 2 inputs and submit
var name = document.createElement("input");
name.placeholder = "enter a name";
var age = document.createElement("input");
age.placeholder = "enter the age";
var submit = document.createElement("input");
submit.type = "submit";
submit.value = "submit";
var form = document.createElement("form");
form.method = "post";
form.appendChild(name);
form.appendChild(age);
form.appendChild(submit);
contenu.appendChild(form);

// create a new empty table
var newTable = [];
var newObject = {};
newObject.name = name.value;//"Tom" will work
newObject.age = age.value;//20 will work
newTable.push(newObject);

// submit the form to show the input value in html
form.addEventListener("submit", function(e){
newTable.forEach(function(table){
e.preventDefault();
var pElt = document.createElement("p");
pElt.innerHTML = table.name + " " + table.age;
contenu.appendChild(pElt);
});
});
});

目标:点击“添加”按钮显示2个输入和“提交”按钮,输入姓名和年龄,然后点击“提交”将它们显示在div中,我把输入的值作为对象的属性值, newObject.name = name.value;newObject.age = Age.value; 但它不起作用,谢谢感谢您的帮助!

最佳答案

我修好了你的 fiddle ,你可以在这里查看:

https://jsfiddle.net/o08mua1y/

    form.addEventListener("submit", function(e){
newObject.name = name.value;//"Tom" will work
newObject.age = age.value;//20 will work
newTable.forEach(function(table){
e.preventDefault();
var pElt = document.createElement("p");
pElt.innerHTML = table.name + " " + table.age;
contenu.appendChild(pElt);
});
});

问题是您试图在创建输入字段的监听器中设置名称和年龄字段的值,而不是在提交输入时触发的监听器中设置。如果您在提交监听器中设置这些值,则在 forEach 循环之前,这些值将被设置,并按预期显示在 HTML 中

关于javascript - 如何在javascript中将输入值设置为对象的属性值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37912983/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com