很抱歉,我是 javascript 新手,所以我想问一些问题。所以我想当我在输入文本中键入数字时突然出现一个选项。例如,如果我在输入文本中键入 2,则会出现 2 个选项。
<input type="num" name="member" id="member" value="">
最佳答案
我认为这可以为您指出正确的方向:
function addOptions() {
// "Reset" the div to prevent unwanted behavior
document.getElementById('selects').innerHTML = "";
// Get the value of your input field
var inputValue = document.getElementById('member').value;
// A loop to append as many selects as required (e. g. if inputValue is 2, 2 selects will appear
for (var i = 0; i < inputValue; i++) {
var select = document.createElement('select'); // Create the select
var option = document.createElement('option'); // Create the option for the select
option.innerText = "Example"; // Set a text for the option
select.appendChild(option); // Append the option to the select
document.getElementById('selects').appendChild(select); // Append the select to the body
}
}
<input type="number" onkeyup="addOptions()" name="member" id="member" value="">
<div id="selects"></div>
与我的编辑相关的注释:
正如我的答案中的评论所述,如果用户更改输入值,将会出现不需要的行为。例如用户输入 2,但将其更改为 4。之后,用户将有 6 个选择,而他们只想有 4 个。
因此,我在脚本中添加了 document.getElementById('selects').innerHTML = "";
以防止出现这种情况。为此,我还更改了脚本以将选择附加到 div,而不是直接附加到正文。
关于javascript - 在输入文本javascript中输入数字时如何显示选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50385267/