简体   繁体   English

如何使用变量引用文本框

[英]How do I reference text boxes using a variable

So I am making a small quiz on JavaScript for the first time. 因此,我第一次进行JavaScript小测验。 I wanted the user to be able to select between 3 options(a, b and c) by entering the letter in a text box and clicking a button to check the answer. 我希望用户能够通过在文本框中输入字母并单击按钮来检查答案,从而在3个选项(a,b和c)之间进行选择。 A text will then appear underneath the text box to show whether the user entered the right option or not. 然后,文本框下方将显示一个文本,以显示用户是否输入了正确的选项。

I have managed to make this work but since there are multiple questions, I wanted to use a for loop to loop through each text box (I named each text box "0", "1" ...) but I cannot reference them using i . 我设法完成了这项工作,但是由于存在多个问题,我想使用一个for循环遍历每个文本框(我将每个文本框命名为“ 0”,“ 1” ...),但是我无法使用i How can I do it? 我该怎么做?

Here is my JavaScript: 这是我的JavaScript:

var answer = ["a", "b", "c"];
var results = "results"

function check() {
    for (i = 1; i = 4; i++) {
        var input = document.getElementById(i).value;

        if (input == answer[parseInt(i-1)]) {
            document.getElementById(results.concat(i)).innerHTML = "Correct";
        }
        else {
            document.getElementById(results.concat(i)).innerHTML = "Wrong";
        }
    }
}

Here is the HTML (I repeated the same code for each question with a different ID): 这是HTML(对于每个问题,我使用不同的ID重复了相同的代码):

<input type="text" id="0" value="a, b or c"><br>
<input type=button value="Check" onClick="check()"><br>
Result: <span id="results0"></span><br><br>

If you have all of these within a <div> or div tag you can reference them using :nth-child notation. 如果所有这些都在<div>或div标记内,则可以使用:nth-​​child表示法引用它们。 This works by referencing the nth child from the beginning. 这通过从头开始引用第n个孩子来工作。

$("div:nth-child(i)");

Looping through id's feels very dirty to me. 遍历id的感觉对我来说很脏。 From a maintenance and readability standpoint, I recommend you loop through a collection of Nodes instead. 从维护和可读性的角度来看,我建议您改为遍历节点集合。

I believe that you are looking for: 我相信您正在寻找:

document.getElementsByClassName("someClass")[0];

Where [0] Would be the index of the element whos class is shared. 其中[0]将是共享whos类的元素的索引。

Here is a code sample I wrote for you to reference using textboxes and outputting the values into a div within a for loop. 这是我编写的代码示例,供您使用文本框供您参考,并将值输出到for循环内的div中。

https://jsfiddle.net/4ocnyy38/1/ https://jsfiddle.net/4ocnyy38/1/

With the html you provided your for loop is incorrect. 使用您提供的HTML,for循环不正确。

Since you started your input at 0 you want to start looping at 0. 由于您从0开始输入,因此您想从0开始循环。

for (i = 0; i <= 2; i++) { //with three values 0,1,2
  ...
}

Your <span> tag also need to be closed with a </span> 您的<span>标记也需要用</span>关闭

This should work: There are a few things wrong with your original code 这应该可以工作:原始代码有些错误

Wrong: 错误:

for (i = 1; i = 4; i++)

usually we start our iterations on 0 index, also the middle portion of the for loop should return truthy which means it should evaluate to true or false "i = 4" will never be either because = is an assignment operator, you should use evaluation operators >, <, >=, ==, etc. 通常我们从0索引开始迭代,for循环的中间部分也应该返回true,这意味着它应该求值为true或false“ i = 4”永远不会是因为=是赋值运算符,所以应该使用求值运算符>,<,> =,==等

for (i = 0; i < 3; i++) {
        var input = document.getElementById(i).value;

        if (input == answer[i]) {
            document.getElementById("results" + i).innerHTML = "Correct";
        }
        else {
            document.getElementById("results" + i).innerHTML = "Wrong";
        }
    }

Additionally you were using "result" like a variable in this: 另外,您在此像变量一样使用“结果”:

results.concat(i)

So results would need to be a variable that contains the string "results" which I doubt is the case. 因此,结果需要是一个包含字符串“结果”的变量,我怀疑情况确实如此。 so what we are telling the getElementById method by doing it this way 所以我们通过这种方式告诉getElementById方法

document.getElementById("results" + i)

is to find an element with an ID of "results" plus the index of the loop eg. 是找到一个ID为“结果”的元素加上循环索引,例如。 id="result0", or id="result1" etc. id =“ result0”或id =“ result1”等。

You can dynamically create inputbox and result span and alot dynamic ids to them and then check the correct answer on click of button 您可以动态创建输入框,并为其生成跨度和大量动态ID,然后单击按钮检查正确答案

Javascript: 使用Javascript:

var answer = ["a", "b", "c"];
var results = "results";
setTimeout(function(){
var injectData='';
for(var i=0;i<3;i++){
injectData+="<input type='text' id='id_"+i+"' placeholder='a, b or c'/> Result: <span id='results_"+i+"'></span><br/>";
}
document.getElementById('inject').innerHTML=injectData;
},500);
function check() {
    for (i = 0; i <3; i++) {
        var input = document.getElementById('id_'+i).value;

        if (input == answer[i]) {
            document.getElementById("results_"+i).innerHTML = "Correct";
        }
        else {
            document.getElementById("results_"+i).innerHTML = "Wrong";
        }
    }
}

HTML: HTML:

<div id="inject">

</div>
<input type=button value="Check" onClick="check();"><br>

Demo: https://jsfiddle.net/9ea46of5/ 演示: https : //jsfiddle.net/9ea46of5/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用Javascript将文本框和按钮添加到表中? - How do I add text boxes and buttons into a table using Javascript? 如何使用jquery添加2个文本框? - How Do I add 2 text boxes with jquery? 如何使用 JavaScript 以一个作为参考来同步两个不同大小的框的滚动 - How do I synchronise scrolling of two different sized boxes using one as a reference using JavaScript 如何存储多个文本框? - How do I store multiple text boxes? 如何通过JQuery更改/更改变量名称以保持名称属性不同来添加/删除文本框? - How do I add/remove text boxes with JQuery changing the variable name to keep the name attributes different? 如何计算两个文本框并在另一个文本框中显示答案? - How do I calculate two text boxes and display the answer in another? 如何动态打印出加载到文本框中的页面? - how do I dynamically print out a page that is loaded into text boxes? 通过文本框循环,使用id作为变量? - Looping through text boxes, using id as a variable? 如何使我的文本保持变量数而不是javascript D3中的引用? - How do I make my text keep the variable number and not the reference in javascript D3? 我想使用事件处理程序引用 img 的 alt 文本。 如何在函数中引用 img 标签 - I want to reference an img's alt text using event handlers. How do I reference the img tag in a function
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM