我在文本输入旁边的html文件中创建了3个复选框。如果输入框被选中,我试图将输入值附加到一个空数组中。我该怎么办?谢谢
function increment(action: AttributeTrait) {
(attributes as
Record<AttributeTrait["category"], {
traits: Record<AttributeTrait["trait"], number>
}>
)[action.category].traits[action.trait]++;
}
上面的代码不起作用。当我调用该函数时,它不会追加。
答案 0 :(得分:2)
question = document.getElementById("question").value;
result1 = document.getElementById("result1").value;
result2 = document.getElementById("result2").value;
result3 = document.getElementById("result3").value;
correctRes1 = document.getElementById("check1");
correctRes2 = document.getElementById("check2");
correctRes3 = document.getElementById("check3");
correct = [];
document.getElementById('do-check-btn').addEventListener('click',doCheck);
function check() {
if (correctRes1.checked == true) {
correct.push(result1);
}
if (correctRes2.checked == true) {
correct.push(result1);
}
if (correctRes3.checked == true) {
correct.push(result3);
}
}
function doCheck(){
check();
raw = JSON.stringify({
question: question,
answer: [result1, result2, result3],
correctAns: correct,
});
document.getElementById("pre-out").innerHTML = raw;
}
<textarea id="question">Here be the question</textarea>
<div><input type="text" id="result1" value="Here be dragons"/><input type="checkbox" id="check1" /></div>
<div><input type="text" id="result2" value="Here be ghosts"/><input type="checkbox" id="check2" /></div>
<div><input type="text" id="result3" value="Here be pirates"/><input type="checkbox" id="check3" /></div>
<button id="do-check-btn">Do Check</button>
<pre id="pre-out"></pre>
我已将您的代码添加到按钮事件中。看看是否可以使它与您想要的东西一起使用。
答案 1 :(得分:0)
这几乎是正确的。唯一的问题是,在加载页面时,该代码仅运行一次。
每次输入复选框发生更改时,您需要add event listeners来运行代码。