我被困在这里...我正在不同的行中回答几个问题,并在下拉菜单中提供是/否答案。当所有问题都得到解答后,我想单击“生成”按钮,并将所有带有是/否答案的问题收集到一个简单的普通段落中的单个“结果”框中。这就是我到目前为止所拥有的(我不知道 html/js 等编码,但我擅长谷歌搜索)。 `
<html>
<body>
<form>
Done it?
<select id="q1">
<option>Yes</option>
<option>No</option>
</select>
<p>
Checked Around?
<select id="q2">
<option>Yes</option>
<option>No</option>
</select>
<p>
<input type="button" onclick="myFunction1()" value="Generate">
<input type="text" id="result" size="25">
</form>
<script>
function myFunction1() {
var no = document.getElementById("q1");
var option = no.options[no.selectedIndex].text;
var txt = document.getElementById("result").value;
txt = txt + option;
document.getElementById("result").value = txt;
}
</script>
</body>
</html>
最佳答案
DEMO
尝试向您的选择添加适当的标签,向表单添加名称,并执行以下操作:
<form name="myForm">
<p>
<label for="q1">Done it?</label>
<select id="q1">
<option>Yes</option>
<option>No</option>
</select>
</p>
<p>
<label for="q2">Checking Around?</label>
<select id="q2">
<option>Yes</option>
<option>No</option>
</select>
</p>
<input type="button" onclick="populateResults()" value="Generate">
<div id="result"></div>
</form>
然后添加提交处理程序:
function populateResults() {
var selects = document.forms.myForm.querySelectorAll('select'),
result = document.getElementById("result");
Array.from(selects).forEach(function(a, i) {
var answer = a.options[a.selectedIndex].text,
question = selects[i].labels[0].textContent;
result.innerHTML += question + ' ' + answer + '<br>';
})
}
关于javascript - 将个性化文本插入 js var no= document.getElementById 结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33637184/