根据用户输入选择JavaScript变量和数组元素

时间:2017-08-27 15:27:38

标签: javascript html css arrays user-input

我想根据用户输入从数组中选择一个元素。我尝试这样做的一个例子如下。用户将输入1,2或3(在此示例中)。然后,根据此输入的结果,将选择其中一个a变量。然后,将选择该变量/数组中的随机元素以显示在段落标记中。

// user input must be 1,2 or 3 (in this example)
<input type="number" id="userInput">
<script>
    var ageNum = [0,1,2];
    var a1 = ["string1.1","string2.1","string3.1"];
    var a2 = ["string1.2","string2.2","string3.2"];
    var a3 = ["string1.3","string2.3","string3.3"];
    var selectedA = ["a"+userInput.toString()];
    var rdnNum = ageNum[Math.floor(Math.random()*ageNum.length)];
    document.getElementById("display_string").innerHTML = selectedA[rdnNum];
</script>

<p id="display_string">...</p>

这只是我尝试过的一个例子(失败了),但我对任何攻击问题的新方法持开放态度。

2 个答案:

答案 0 :(得分:0)

试试这个

var a1 = ["string1.1","string2.1","string3.1"],
    a2 = ["string1.2","string2.2","string3.2"],
    a3 = ["string1.3","string2.3","string3.3"];


var input = document.querySelector("input[type=number]"),
inputValue= input.addEventListener("input",function(){
    var currentValue = this.value;
    if (currentValue >0 && currentValue <4 ){
         if(currentValue === 1){ /*a1*/}
         elseif(currentValue === 2){ /*a2*/}
         else(currentValue === 2){ /*a3*/ }
    } 
}, false)
<input type="number" id="userInput">

更清洁的代码

var a1 = ["string1.1","string2.1","string3.1"],
    a2 = ["string1.2","string2.2","string3.2"],
    a3 = ["string1.3","string2.3","string3.3"];

 
var input = document.querySelector("input[type=number]"),
inputValue= input.addEventListener("input",function(){
    var currentValue = this.value;
    if (["1", "2", "3"].includes(currentValue)){
        
         var myArray = "a"+currentValue;
          alert(myArray);
    } 
}, false)
<input type="number" id="userInput">

答案 1 :(得分:0)

您应该处理二维数组以轻松获取相应的消息。 DOM元素是基于事件的。所以,你应该使用事件监听器。

var msgs = [
["string1.1","string2.1","string3.1"], // a1
["string1.2","string2.2","string3.2"], // a2
["string1.3","string2.3","string3.3"]  // a3
];

document.getElementById('userInput').addEventListener('change', function (e) {
  var selectedArray = msgs[parseInt(e.target.value)];
  var randomIdx = parseInt(Math.random() * selectedArray.length);
    var randomMessage = selectedArray[randomIdx]
    document.getElementById("display_string").innerHTML = randomMessage
});

Check this fiddle to see my approach