gpt4 book ai didi

Javascript,添加输入字段会清空所有其他输入字段

转载 作者:行者123 更新时间:2023-11-29 20:01:23 25 4
gpt4 key购买 nike

我正在创建一段 Javascript 代码,您可以在其中创建具有多个答案的多个问题。问题数量最多为 20 个。当我点击“添加问题”时,它会添加一个有两个答案的问题。当我填写一些输入字段并单击“添加问题”时,它会清空我所有的文本字段。这怎么可能?

var fields = 0;
var qAmount = 0;
var array = new Array();

function addInput() {
if (fields != 2) {
qAmount++;
var element = document.getElementById('texty');
element.innerHTML += "" +
"<label>Question " + qAmount + "</label><span class='field'><input type='text' class='longinput' name='question" + qAmount + "' /></span>" +
"<span class='field'><input type='radio' name='question" + qAmount + "-correctanswer' value='answer" + qAmount + "-1' /> <input type='text' name='answer" + qAmount + "-1'> Answer 1</input></span>" +
"<span class='field'><input type='radio' name='question" + qAmount + "-correctanswer' value='answer" + qAmount + "-2' /> <input type='text' name='answer" + qAmount + "-2'> Answer 2</input></span>" +
"<div id='a" + qAmount + "'></div><br/>" +
"<span class='field'><a style='cursor: pointer' onclick='addAnswer(" + qAmount + ")'>Add answer</a></span><br /><br />";
fields += 1;
array[qAmount] = 2;
}
}

最佳答案

问题是,当您执行 element.innerHTML += ... 时,您正在对页面上已存在的内容进行浅拷贝,然后将其作为覆盖重新插入。所以你没有保留已经输入的值。您应该做的是将新的 dom 元素附加到元素。

这里是如何从 HTML 字符串创建元素的链接:Creating a new DOM element from an HTML string using built-in DOM methods or prototype

以及如何将它们附加到元素:https://developer.mozilla.org/en-US/docs/DOM/Node.appendChild

像这样的东西应该可以解决问题:(可能需要一些调试)

var fields = 0;
var qAmount = 0;
var array = new Array();
var element = document.getElementById('texty');

function addInput() {
var div, s;
if (fields != 2) {
qAmount++;
s = "<label>Question " + qAmount + "</label><span class='field'><input type='text' class='longinput' name='question" + qAmount + "' /></span>" +
"<span class='field'><input type='radio' name='question" + qAmount + "-correctanswer' value='answer" + qAmount + "-1' /> <input type='text' name='answer" + qAmount + "-1'> Answer 1</input></span>" +
"<span class='field'><input type='radio' name='question" + qAmount + "-correctanswer' value='answer" + qAmount + "-2' /> <input type='text' name='answer" + qAmount + "-2'> Answer 2</input></span>" +
"<div id='a" + qAmount + "'></div><br/>" +
"<span class='field'><a style='cursor: pointer' onclick='addAnswer(" + qAmount + ")'>Add answer</a></span><br /><br />";
div = document.createElement('div');
div.innerHTML = s;
element.appendChild(div);
fields += 1;
array[qAmount] = 2;
}
}

关于Javascript,添加输入字段会清空所有其他输入字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14327359/

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