[英]How to create flexible input-fields in Javascript?
I am having problems to create the following situation:我在创建以下情况时遇到问题:
I want to create inputfields, where I can write "1", "2" or "3" in any order, but each number is only allowed to be writen once.我想创建输入字段,我可以在其中以任何顺序写入“1”、“2”或“3”,但每个数字只允许写入一次。
Repeating one of those three numbers and writing other numbers than those three in the inputfields should be considered bad.重复这三个数字之一并在输入字段中写入除这三个数字之外的其他数字应该被认为是不好的。
What do I need to add to the code?我需要在代码中添加什么?
a = 1 b = 2 c = 3 L = a L = b L = c function F1() { feedBack = document.getElementById("feedBack"); an = document.getElementById("userAnswer"); L = document.getElementById("L").textContent; if (an == L) { feedBack.textContent = "good"; } else { feedBack.textContent = "bad"; } }
<input id="userAnswer" type=text> <input id="userAnswer" type=text> <input id="userAnswer" type=text> <button onclick="F1()">check</button> <label id="L"> </label> <p id="feedBack"> </p>
You could try to loop over the input elements and then validate each element, in the loop save the value of the input in a set/array for each input so with this we would have a cache to check the input field values.您可以尝试遍历输入元素,然后验证每个元素,在循环中将输入的值保存在每个输入的集合/数组中,这样我们就有了一个缓存来检查输入字段值。
function validate() { let numberEntered = new Set(); let allowedValues = [1, 2, 3]; let inputStatus = false; let feedBack = document.getElementById("feedBack"); let inputEle = document.querySelectorAll(".number-field"); for (let input of inputEle) { let value = parseInt(input.value); if (allowedValues.includes(value) && !numberEntered.has(value)) { numberEntered.add(value) } else { inputStatus = true; break; } } if (inputStatus) { feedBack.textContent = "Bad"; } else { feedBack.textContent = "good"; } }
<input id="userAnswer1" class="number-field" type=text> <input id="userAnswer2" class="number-field" type=text> <input id="userAnswer3" class="number-field" type=text> <button onclick="validate()">check</button> <label id="L"> </label> <p id="feedBack"> </p>
It's worth mentioning (especially for the more novice JavaScripters reading this) that, as with most programming problems, there are lots of ways to correctly satisfy the requirements from the original question.值得一提的是(特别是对于阅读本文的 JavaScript 新手),与大多数编程问题一样,有很多方法可以正确满足原始问题的要求。
I know this isn't Code Review.SE , but you might benefit from some feedback on the example you provided, if you're interested:我知道这不是Code Review.SE ,但如果您有兴趣,您可能会从对您提供的示例的一些反馈中受益:
a
, b
, and c
are never used in any particularly useful way, and detract from the human readability of your code.变量a
、 b
和c
从未以任何特别有用的方式使用,并且会降低代码的可读性。 You should probably remove their declarations entirely.您可能应该完全删除他们的声明。L
three times consecutively.您连续三次设置变量L
This doesn't do very much at all, considering also L
is overridden once F1()
is executed.考虑到一旦F1()
被执行, L
也会被覆盖,这根本没有多大作用。 You should probably remove these unnecessary assignments entirely.您可能应该完全删除这些不必要的分配。ID
values should be unique across the entire document
space; HTML 规范明确规定ID
值在整个document
空间中应该是唯一的; anything else is invalid and can lead to headaches and undocumented behavior down the line, especially when JavaScript comes into play.其他任何东西都是无效的,可能会导致头痛和未记录的行为,尤其是当 JavaScript 发挥作用时。 In the simplified example, there really isn't any need to assign them ID
s at all (see solution).在简化的示例中,实际上根本不需要为它们分配ID
(请参阅解决方案)。onclick
attribute) is generally regarded as an outdated concept.相对较小,但内联事件处理(即使用onclick
属性)通常被认为是一个过时的概念。 Instead, use the addEventListener()
paradigm to make your code easier to interpret and debug.相反,使用addEventListener()
范例使您的代码更易于解释和调试。F1()
isn't particularly descriptive to what the function actually does when called.函数名称F1()
并没有特别描述函数在调用时实际执行的操作。 A future developer maintaining your code would have a less difficult time discerning what this method does if it was named something more descriptive, like validateForm()
, or even just validate()
.如果该方法被命名为更具描述性的名称,例如validateForm()
,或者甚至只是validate()
,那么维护您的代码的未来开发人员将更容易辨别该方法的作用。 To satisfy your requirements, you might look to write something more like what I've got below.为了满足您的要求,您可能希望编写更类似于我在下面得到的内容。 In a nutshell, when the validate()
function is run, the following actions are taken:简而言之,当运行validate()
函数时,会执行以下操作:
validNumbers
, an array of the valid inputs to be validated against he fields.实例化validNumbers
,一个要针对字段进行验证的有效输入数组。inputFields
which evaluates to a NodeList
iterable which can be looped.实例化inputFields
,其计算结果为可循环的NodeList
可迭代对象。feedbackElement
, a reference to your <p>
node in the DOM.实例化feedbackElement
,一个对 DOM 中<p>
节点的引用。inputFields
, and checks if the value of the current field
is in the validNumbers
array.循环所有inputFields
,并检查当前field
的值是否在validNumbers
数组中。validNumbers
array (as it's already been used and can't be used again) and proceed to validate the next field.如果验证成功,代码会从validNumbers
数组中删除有效值(因为它已经被使用并且不能再次使用)并继续验证下一个字段。"bad"
and breaks out of the validation loop.如果验证不成功,代码会自动将您的反馈元素的文本设置为"bad"
并退出验证循环。validNumbers
left.验证所有三个输入字段后,代码会检查是否还有validNumbers
任何剩余元素。 If there are, not all elements were used and the feedback is once again set to "bad"
.如果有,则并非所有元素都被使用,并且反馈再次设置为"bad"
。 Otherwise, the validation checks out and the feedback element's contents are set to "good"
.否则,验证将被检出并且反馈元素的内容被设置为"good"
。 function validate() { var validNumbers = [1, 2, 3]; var inputFields = document.querySelectorAll("input[type='text']"); var feedbackElement = document.querySelector("p#feedBack"); for (field of inputFields) { var fieldValue = parseInt(field.value); if (validNumbers.includes(fieldValue)) { // valid number & not encountered yet validNumbers.splice(validNumbers.indexOf(fieldValue), 1); } else { // invalid number or already used feedbackElement.innerText = "bad"; break; // break out of `for` loop, as there's already no possible way for the provided numbers to be "good" } } if (validNumbers.length === 0) { // all numbers were used feedbackElement.innerText = "good"; } else { // not all numbers were used feedbackElement.innerText = "bad"; } } document.querySelector("button").addEventListener('click', function() { validate(); });
<input type=text> <input type=text> <input type=text> <button>check</button> <p id="feedBack"> </p>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.