用户输入任何数字,但只输入可被3整除并显示回来的商店编号

时间:2018-11-25 13:53:30

标签: javascript arrays

准备脚本以将数据存储到数组中。用户可以输入任何数字,但只能存储可被数字三除的值。然后,在HTML页面上显示回数据(存储在Array中)。

我需要使用JavaScript代码执行此操作。如何存储价值和显示价值?谢谢。

2 个答案:

答案 0 :(得分:1)

这是您所需要的吗?

var numbers = []; // Array to store the valid numbers

function openPromt() {
 var num = prompt("Please enter a number", "0");
 storeIfNumValid(num);
}

openPromt();

// funtion that will call after each value from `prompt`
function storeIfNumValid(num) {
 if (num != null && num % 3 === 0) {
  numbers.push(num);
  openPromt();
 } else {
  console.log(numbers);
  document.getElementById("demo").innerHTML = numbers;
 }
}
<div id="demo"></div>

答案 1 :(得分:0)

var array = [];
 $(document).ready(function() {
$("#yourInputId").keydown(function (e) {
    // Allow: backspace, delete, tab, escape, enter and .
    if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110, 190]) !== -1 ||
         // Allow: Ctrl/cmd+A
        (e.keyCode == 65 && (e.ctrlKey === true || e.metaKey === true)) ||
         // Allow: Ctrl/cmd+C
        (e.keyCode == 67 && (e.ctrlKey === true || e.metaKey === true)) ||
         // Allow: Ctrl/cmd+X
        (e.keyCode == 88 && (e.ctrlKey === true || e.metaKey === true)) ||
         // Allow: home, end, left, right
        (e.keyCode >= 35 && e.keyCode <= 39)) {
             // let it happen, don't do anything
             return;
    }
    // Ensure that it is a number and stop the keypress
    if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
        e.preventDefault();
    }
   });
   });
     var SOMENAME = document.getElementById('yourInputId').value
     if(SOMENAME % 3 == 0){
    array.push(SOMENAME);
      for (numb = 0; numb < array.length; numb++)
    document.write(array[i]);
    }
     else{
     console.log('error')}     //u can do anything if 'IF' condition is false